详解SpringMVC使⽤MultipartFile实现⽂件的上传
如果需要实现跨服务器上传⽂件,就是将我们本地的⽂件上传到资源服务器上,⽐较好的办法就是通过ftp上传。这⾥是结合SpringMVC+ftp的形式上传的。我们需要先懂得如何配置springMVC,然后在配置ftp,最后再结合MultipartFile上传⽂件。springMVC上传需要⼏个关键jar包,spring以及关联包可以⾃⼰配置,这⾥主要说明关键的jar包
1:spring-web-3.2.9.RELEASE.jar (spring的关键jar包,版本可以⾃⼰选择)
2:commons-io-2.2.jar (项⽬中⽤来处理IO的⼀些⼯具类包)
配置⽂件
SpringMVC是⽤MultipartFile来进⾏⽂件上传的,因此我们先要配置MultipartResolver,⽤于处理表单中的file
<!-- 上传⽂件解释器 -->
<bean id="multipartResolver" class="org.springframework.web.multipartmons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8" />
<property name="maxUploadSize" value="10485760" />
<property name="maxInMemorySize" value="4096" />
<property name="resolveLazily" value="true" />
</bean>
其中属性详解:
defaultEncoding配置请求的编码格式,默认为iso-8859-1
maxUploadSize配置⽂件的最⼤单位,单位为字节
maxInMemorySize配置上传⽂件的缓存,单位为字节
resolveLazily属性启⽤是为了推迟⽂件解析,以便在UploadAction 中捕获⽂件⼤⼩异常
页⾯配置
在页⾯的form中加上enctype="multipart/form-data"
<form id="" name="" method="post" action="" enctype="multipart/form-data">
表单标签中设置enctype="multipart/form-data"来确保匿名上载⽂件的正确编码。
是设置表单的MIME编码。默认情况,这个编码格式是application/x-www-form-urlencoded,不能⽤于⽂件上传;只有使⽤了multipart/form-data,才能完整的传递⽂件数据,进⾏下⾯的操作。enctype="multipart/form-data"是上传⼆进制数据。form⾥⾯的input的值以2进制的⽅式传过去,所以request就得不到值了。
编写上传控制类
编写⼀个上传⽅法,这⾥没有返回结果,需要跳转页⾯或者返回其他值可以将void改为String、Map<String,Object>等值,再return返回结果。
/**
* 上传
* @param request
* @return
*/
@ResponseBody
@RequestMapping(value = "/upload", method = {RequestMethod.GET, RequestMethod.POST})
public void upload(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request;
MultipartFile file = File("file");//file是页⾯input的name名
String basePath = "⽂件路径"
try {
MultipartResolver resolver = new Session().getServletContext());
if (resolver.isMultipart(request)) {
String fileStoredPath = "⽂件夹路径";
//随机⽣成⽂件名
String randomName = RandomFileName();
String uploadFileName = OriginalFilename();
if (StringUtils.isNotBlank(uploadFileName)) {
//截取⽂件格式名
String suffix = uploadFileName.substring(uploadFileName.indexOf("."));
//重新拼装⽂件名
String newFileName = randomName + suffix;
String savePath = basePath + "/" + newFileName;
File saveFile = new File(savePath);
File parentFile = ParentFile();
if (ists()) {
saveFile.delete();
} else {
if (!ists()) {
parentFile.mkdirs();
}
}
//复制⽂件到指定路径
//上传⽂件到服务器
FTPClientUtil.upload(saveFile, fileStoredPath);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
FTP客户端上传⼯具
package com.yuandingmon.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.SocketException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import org.apachemons.lang.StringUtils;
import org.apachemons.ftp.FTP;spring framework组件
import org.apachemons.ftp.FTPClient;
import org.apachemons.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* FTP客户端⼯具
*/
public class FTPClientUtil {
/**
* ⽇志
*/
private static final Logger LOGGER = Logger(FTPClientUtil.class);  /**
* FTP server configuration--IP key,value is type of String
*/
public static final String SERVER_IP = "SERVER_IP";
/**
* FTP server configuration--Port key,value is type of Integer
*/
public static final String SERVER_PORT = "SERVER_PORT";
/**
* FTP server configuration--ANONYMOUS Log in key, value is type of Boolean
*/
public static final String IS_ANONYMOUS = "IS_ANONYMOUS";
/
**
* user name of anonymous log in
*/
public static final String ANONYMOUS_USER_NAME = "anonymous";
/**
* password of anonymous log in
*/
public static final String ANONYMOUS_PASSWORD = "";
/**
* FTP server configuration--log in user name, value is type of String
*/
public static final String USER_NAME = "USER_NAME";
/**
* FTP server configuration--log in password, value is type of String
*/
public static final String PASSWORD = "PASSWORD";
/**
* FTP server configuration--PASV key, value is type of Boolean
*/
public static final String IS_PASV = "IS_PASV";
/**
* FTP server configuration--working directory key, value is type of String While logging in, the current di
rectory    * is the user's home directory, the workingDirectory must be set based on it. Besides, the workingDirectory must    * exist, it can not be created automatically. If not exist, file will be uploaded in the user's home directory. If
* not assigned, "/" is used.
*/
public static final String WORKING_DIRECTORY = "WORKING_DIRECTORY";
public static Map<String, Object> serverCfg = new HashMap<String, Object>();
static Properties prop;
static{
LOGGER.info("开始加载ftp.properties⽂件!");
prop = new Properties();
try {
InputStream fps = ResourceAsStream("/ftp.properties");
prop.load(fps);
fps.close();
} catch (Exception e) {
<("读取ftp.properties⽂件异常!",e);
}
serverCfg.put(FTPClientUtil.SERVER_IP, values("SERVER_IP"));
serverCfg.put(FTPClientUtil.SERVER_PORT, Integer.parseInt(values("SERVER_PORT")));
serverCfg.put(FTPClientUtil.USER_NAME, values("USER_NAME"));
serverCfg.put(FTPClientUtil.PASSWORD, values("PASSWORD"));
LOGGER.info(String.valueOf(serverCfg));
}
/**
* Upload a file to FTP server.
*
* @param serverCfg : FTP server configuration
* @param filePathToUpload : path of the file to upload
* @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced    *      by the file name to upload
* @throws IOException
* @throws SocketException
*/
public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredName)      throws SocketException, IOException {
upload(serverCfg, new File(filePathToUpload), fileStoredName);
}
/**
* Upload a file to FTP server.
*
* @param serverCfg : FTP server configuration
* @param fileToUpload : file to upload
* @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced    *      by the file name to upload
* @throws IOException
* @throws SocketException
*/
public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredName)
throws SocketException, IOException {
if (!ists()) {
throw new IllegalArgumentException("File to upload does not exists:" + AbsolutePath ());
}
if (!fileToUpload.isFile()) {
throw new IllegalArgumentException("File to upload is not a file:" + AbsolutePath());
}
if (StringUtils.isBlank((String) (SERVER_IP))) {
throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration.");
}
transferFile(true, serverCfg, fileToUpload, fileStoredName, null, null);
}
/**
* Download a file from FTP server
*
* @param serverCfg : FTP server configuration
* @param fileNameToDownload : file name to be downloaded
* @param fileStoredPath : stored path of the downloaded file in local
* @throws SocketException
* @throws IOException
*/
public static final void download(Map<String, Object> serverCfg, String fileNameToDownload, String fileStoredPath)      throws SocketException, IOException {
if (StringUtils.isBlank(fileNameToDownload)) {
throw new IllegalArgumentException("File name to be downloaded can not be blank.");
}
if (StringUtils.isBlank(fileStoredPath)) {
throw new IllegalArgumentException("Stored path of the downloaded file in local can not be blank.");
}
if (StringUtils.isBlank((String) (SERVER_IP))) {
throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration.");
}
transferFile(false, serverCfg, null, null, fileNameToDownload, fileStoredPath);
}
private static final void transferFile(boolean isUpload, Map<String, Object> serverCfg, File fileToUpload,
String serverFileStoredName, String fileNameToDownload, String localFileStoredPath) throws  SocketException,
IOException {
String host = (String) (SERVER_IP);
Integer port = (Integer) (SERVER_PORT);
Boolean isAnonymous = (Boolean) (IS_ANONYMOUS);
String username = (String) (USER_NAME);
String password = (String) (PASSWORD);
Boolean isPASV = (Boolean) (IS_PASV);
String workingDirectory = (String) (WORKING_DIRECTORY);
FTPClient ftpClient = new FTPClient();
InputStream fileIn = null;
OutputStream fileOut = null;
try {
if (port == null) {
LOGGER.debug("Connect to FTP server on " + host + ":" + FTP.DEFAULT_PORT);
} else {
LOGGER.debug("Connect to FTP server on " + host + ":" + port);
}
int reply = ReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
<("FTP server refuses connection");
return;
}
if (isAnonymous != null && isAnonymous) {
username = ANONYMOUS_USER_NAME;
password = ANONYMOUS_PASSWORD;
}
LOGGER.debug("Log in FTP server with username = " + username + ", password = " + password);
if (!ftpClient.login(username, password)) {
<("Fail to log in FTP server with username = " + username + ", password = " +  password);
ftpClient.logout();
return;
}
// Here we will use the BINARY mode as the transfer file type,
// ASCII mode is not supportted.
LOGGER.debug("Set type of the file, which is to upload, to BINARY.");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if (isPASV != null && isPASV) {
LOGGER.debug("Use the PASV mode to transfer file.");
} else {
LOGGER.debug("Use the ACTIVE mode to transfer file.");
}
if (StringUtils.isBlank(workingDirectory)) {
workingDirectory = "/";
}
LOGGER.debug("Change current working directory to " + workingDirectory);
changeWorkingDirectory(ftpClient,workingDirectory);
if (isUpload) { // upload
if (StringUtils.isBlank(serverFileStoredName)) {
serverFileStoredName = Name();
}
fileIn = new FileInputStream(fileToUpload);
LOGGER.debug("Upload file : " + AbsolutePath() + " to FTP server with name : "            + serverFileStoredName);
if (!ftpClient.storeFile(serverFileStoredName, fileIn)) {
<("Fail to upload file, " + ReplyString());
} else {
LOGGER.debug("Success to upload file.");
}
} else { // download
// make sure the file directory exists
File fileStored = new File(localFileStoredPath);
if (!ParentFile().exists()) {
}
fileOut = new FileOutputStream(fileStored);
LOGGER.debug("Download file : " + fileNameToDownload + " from FTP server to local : "
+ localFileStoredPath);
if (!ieveFile(fileNameToDownload, fileOut)) {
<("Fail to download file, " + ReplyString());
} else {
LOGGER.debug("Success to download file.");
}
}
ftpClient.logout();
} finally {
if (ftpClient.isConnected()) {
try {
ftpClient.disconnect();
} catch (IOException f) {
}
}
if (fileIn != null) {
try {
fileIn.close();
} catch (IOException e) {
}
}
if (fileOut != null) {
try {
fileOut.close();
} catch (IOException e) {
}
}
}
}

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。