详解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
<!--上传文件解释器--> <beanid="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <propertyname="defaultEncoding"value="utf-8"/> <propertyname="maxUploadSize"value="10485760"/> <propertyname="maxInMemorySize"value="4096"/> <propertyname="resolveLazily"value="true"/> </bean>
其中属性详解:
defaultEncoding配置请求的编码格式,默认为iso-8859-1
maxUploadSize配置文件的最大单位,单位为字节
maxInMemorySize配置上传文件的缓存,单位为字节
resolveLazily属性启用是为了推迟文件解析,以便在UploadAction中捕获文件大小异常
页面配置
在页面的form中加上enctype="multipart/form-data"
<formid=""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返回结果。
/**
*上传
*@paramrequest
*@return
*/
@ResponseBody
@RequestMapping(value="/upload",method={RequestMethod.GET,RequestMethod.POST})
publicvoidupload(HttpServletRequestrequest){
MultipartHttpServletRequestmultipartRequest=(MultipartHttpServletRequest)request;
MultipartFilefile=multipartRequest.getFile("file");//file是页面input的name名
StringbasePath="文件路径"
try{
MultipartResolverresolver=newCommonsMultipartResolver(request.getSession().getServletContext());
if(resolver.isMultipart(request)){
StringfileStoredPath="文件夹路径";
//随机生成文件名
StringrandomName=StringUtil.getRandomFileName();
StringuploadFileName=file.getOriginalFilename();
if(StringUtils.isNotBlank(uploadFileName)){
//截取文件格式名
Stringsuffix=uploadFileName.substring(uploadFileName.indexOf("."));
//重新拼装文件名
StringnewFileName=randomName+suffix;
StringsavePath=basePath+"/"+newFileName;
FilesaveFile=newFile(savePath);
FileparentFile=saveFile.getParentFile();
if(saveFile.exists()){
saveFile.delete();
}else{
if(!parentFile.exists()){
parentFile.mkdirs();
}
}
//复制文件到指定路径
FileUtils.copyInputStreamToFile(file.getInputStream(),saveFile);
//上传文件到服务器
FTPClientUtil.upload(saveFile,fileStoredPath);
}
}
}catch(Exceptione){
e.printStackTrace();
}
}
FTP客户端上传工具
packagecom.yuanding.common.util;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.net.SocketException;
importjava.util.HashMap;
importjava.util.Map;
importjava.util.Properties;
importorg.apache.commons.lang.StringUtils;
importorg.apache.commons.net.ftp.FTP;
importorg.apache.commons.net.ftp.FTPClient;
importorg.apache.commons.net.ftp.FTPReply;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
/**
*FTP客户端工具
*/
publicclassFTPClientUtil{
/**
*日志
*/
privatestaticfinalLoggerLOGGER=LoggerFactory.getLogger(FTPClientUtil.class);
/**
*FTPserverconfiguration--IPkey,valueistypeofString
*/
publicstaticfinalStringSERVER_IP="SERVER_IP";
/**
*FTPserverconfiguration--Portkey,valueistypeofInteger
*/
publicstaticfinalStringSERVER_PORT="SERVER_PORT";
/**
*FTPserverconfiguration--ANONYMOUSLoginkey,valueistypeofBoolean
*/
publicstaticfinalStringIS_ANONYMOUS="IS_ANONYMOUS";
/**
*usernameofanonymouslogin
*/
publicstaticfinalStringANONYMOUS_USER_NAME="anonymous";
/**
*passwordofanonymouslogin
*/
publicstaticfinalStringANONYMOUS_PASSWORD="";
/**
*FTPserverconfiguration--loginusername,valueistypeofString
*/
publicstaticfinalStringUSER_NAME="USER_NAME";
/**
*FTPserverconfiguration--loginpassword,valueistypeofString
*/
publicstaticfinalStringPASSWORD="PASSWORD";
/**
*FTPserverconfiguration--PASVkey,valueistypeofBoolean
*/
publicstaticfinalStringIS_PASV="IS_PASV";
/**
*FTPserverconfiguration--workingdirectorykey,valueistypeofStringWhileloggingin,thecurrentdirectory
*istheuser'shomedirectory,theworkingDirectorymustbesetbasedonit.Besides,theworkingDirectorymust
*exist,itcannotbecreatedautomatically.Ifnotexist,filewillbeuploadedintheuser'shomedirectory.If
*notassigned,"/"isused.
*/
publicstaticfinalStringWORKING_DIRECTORY="WORKING_DIRECTORY";
publicstaticMap<String,Object>serverCfg=newHashMap<String,Object>();
staticPropertiesprop;
static{
LOGGER.info("开始加载ftp.properties文件!");
prop=newProperties();
try{
InputStreamfps=FTPClientUtil.class.getResourceAsStream("/ftp.properties");
prop.load(fps);
fps.close();
}catch(Exceptione){
LOGGER.error("读取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));
}
/**
*UploadafiletoFTPserver.
*
*@paramserverCfg:FTPserverconfiguration
*@paramfilePathToUpload:pathofthefiletoupload
*@paramfileStoredName:thenametogivetheremotestoredfile,null,""andotherblankwordwillbereplaced
*bythefilenametoupload
*@throwsIOException
*@throwsSocketException
*/
publicstaticfinalvoidupload(Map<String,Object>serverCfg,StringfilePathToUpload,StringfileStoredName)
throwsSocketException,IOException{
upload(serverCfg,newFile(filePathToUpload),fileStoredName);
}
/**
*UploadafiletoFTPserver.
*
*@paramserverCfg:FTPserverconfiguration
*@paramfileToUpload:filetoupload
*@paramfileStoredName:thenametogivetheremotestoredfile,null,""andotherblankwordwillbereplaced
*bythefilenametoupload
*@throwsIOException
*@throwsSocketException
*/
publicstaticfinalvoidupload(Map<String,Object>serverCfg,FilefileToUpload,StringfileStoredName)
throwsSocketException,IOException{
if(!fileToUpload.exists()){
thrownewIllegalArgumentException("Filetouploaddoesnotexists:"+fileToUpload.getAbsolutePath
());
}
if(!fileToUpload.isFile()){
thrownewIllegalArgumentException("Filetouploadisnotafile:"+fileToUpload.getAbsolutePath());
}
if(StringUtils.isBlank((String)serverCfg.get(SERVER_IP))){
thrownewIllegalArgumentException("SERVER_IPmustbecontainedintheFTPserverconfiguration.");
}
transferFile(true,serverCfg,fileToUpload,fileStoredName,null,null);
}
/**
*DownloadafilefromFTPserver
*
*@paramserverCfg:FTPserverconfiguration
*@paramfileNameToDownload:filenametobedownloaded
*@paramfileStoredPath:storedpathofthedownloadedfileinlocal
*@throwsSocketException
*@throwsIOException
*/
publicstaticfinalvoiddownload(Map<String,Object>serverCfg,StringfileNameToDownload,StringfileStoredPath)
throwsSocketException,IOException{
if(StringUtils.isBlank(fileNameToDownload)){
thrownewIllegalArgumentException("Filenametobedownloadedcannotbeblank.");
}
if(StringUtils.isBlank(fileStoredPath)){
thrownewIllegalArgumentException("Storedpathofthedownloadedfileinlocalcannotbeblank.");
}
if(StringUtils.isBlank((String)serverCfg.get(SERVER_IP))){
thrownewIllegalArgumentException("SERVER_IPmustbecontainedintheFTPserverconfiguration.");
}
transferFile(false,serverCfg,null,null,fileNameToDownload,fileStoredPath);
}
privatestaticfinalvoidtransferFile(booleanisUpload,Map<String,Object>serverCfg,FilefileToUpload,
StringserverFileStoredName,StringfileNameToDownload,StringlocalFileStoredPath)throws
SocketException,
IOException{
Stringhost=(String)serverCfg.get(SERVER_IP);
Integerport=(Integer)serverCfg.get(SERVER_PORT);
BooleanisAnonymous=(Boolean)serverCfg.get(IS_ANONYMOUS);
Stringusername=(String)serverCfg.get(USER_NAME);
Stringpassword=(String)serverCfg.get(PASSWORD);
BooleanisPASV=(Boolean)serverCfg.get(IS_PASV);
StringworkingDirectory=(String)serverCfg.get(WORKING_DIRECTORY);
FTPClientftpClient=newFTPClient();
InputStreamfileIn=null;
OutputStreamfileOut=null;
try{
if(port==null){
LOGGER.debug("ConnecttoFTPserveron"+host+":"+FTP.DEFAULT_PORT);
ftpClient.connect(host);
}else{
LOGGER.debug("ConnecttoFTPserveron"+host+":"+port);
ftpClient.connect(host,port);
}
intreply=ftpClient.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){
LOGGER.error("FTPserverrefusesconnection");
return;
}
if(isAnonymous!=null&&isAnonymous){
username=ANONYMOUS_USER_NAME;
password=ANONYMOUS_PASSWORD;
}
LOGGER.debug("LoginFTPserverwithusername="+username+",password="+password);
if(!ftpClient.login(username,password)){
LOGGER.error("FailtologinFTPserverwithusername="+username+",password="+
password);
ftpClient.logout();
return;
}
//HerewewillusetheBINARYmodeasthetransferfiletype,
//ASCIImodeisnotsupportted.
LOGGER.debug("Settypeofthefile,whichistoupload,toBINARY.");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
if(isPASV!=null&&isPASV){
LOGGER.debug("UsethePASVmodetotransferfile.");
ftpClient.enterLocalPassiveMode();
}else{
LOGGER.debug("UsetheACTIVEmodetotransferfile.");
ftpClient.enterLocalActiveMode();
}
if(StringUtils.isBlank(workingDirectory)){
workingDirectory="/";
}
LOGGER.debug("Changecurrentworkingdirectoryto"+workingDirectory);
changeWorkingDirectory(ftpClient,workingDirectory);
if(isUpload){//upload
if(StringUtils.isBlank(serverFileStoredName)){
serverFileStoredName=fileToUpload.getName();
}
fileIn=newFileInputStream(fileToUpload);
LOGGER.debug("Uploadfile:"+fileToUpload.getAbsolutePath()+"toFTPserverwithname:"
+serverFileStoredName);
if(!ftpClient.storeFile(serverFileStoredName,fileIn)){
LOGGER.error("Failtouploadfile,"+ftpClient.getReplyString());
}else{
LOGGER.debug("Successtouploadfile.");
}
}else{//download
//makesurethefiledirectoryexists
FilefileStored=newFile(localFileStoredPath);
if(!fileStored.getParentFile().exists()){
fileStored.getParentFile().mkdirs();
}
fileOut=newFileOutputStream(fileStored);
LOGGER.debug("Downloadfile:"+fileNameToDownload+"fromFTPservertolocal:"
+localFileStoredPath);
if(!ftpClient.retrieveFile(fileNameToDownload,fileOut)){
LOGGER.error("Failtodownloadfile,"+ftpClient.getReplyString());
}else{
LOGGER.debug("Successtodownloadfile.");
}
}
ftpClient.noop();
ftpClient.logout();
}finally{
if(ftpClient.isConnected()){
try{
ftpClient.disconnect();
}catch(IOExceptionf){
}
}
if(fileIn!=null){
try{
fileIn.close();
}catch(IOExceptione){
}
}
if(fileOut!=null){
try{
fileOut.close();
}catch(IOExceptione){
}
}
}
}
privatestaticfinalbooleanchangeWorkingDirectory(FTPClientftpClient,StringworkingDirectory)throwsIOException{
if(!ftpClient.changeWorkingDirectory(workingDirectory)){
String[]paths=workingDirectory.split("/");
for(inti=0;i<paths.length;i++){
if(!"".equals(paths[i])){
if(!ftpClient.changeWorkingDirectory(paths[i])){
ftpClient.makeDirectory(paths[i]);
ftpClient.changeWorkingDirectory(paths[i]);
}
}
}
}
returntrue;
}
publicstaticfinalvoidupload(Map<String,Object>serverCfg,StringfilePathToUpload,StringfileStoredPath,String
fileStoredName)
throwsSocketException,IOException{
upload(serverCfg,newFile(filePathToUpload),fileStoredPath,fileStoredName);
}
publicstaticfinalvoidupload(Map<String,Object>serverCfg,FilefileToUpload,StringfileStoredPath,String
fileStoredName)
throwsSocketException,IOException{
if(fileStoredPath!=null&&!"".equals(fileStoredPath)){
serverCfg.put(WORKING_DIRECTORY,fileStoredPath);
}
upload(serverCfg,fileToUpload,fileStoredName);
}
publicstaticfinalvoidupload(StringfilePathToUpload,StringfileStoredPath)throwsSocketException,IOException{
upload(serverCfg,filePathToUpload,fileStoredPath,"");
}
publicstaticfinalvoidupload(FilefileToUpload,StringfileStoredPath)throwsSocketException,IOException{
upload(serverCfg,fileToUpload,fileStoredPath,"");
}
publicstaticStringvalues(Stringkey){
Stringvalue=prop.getProperty(key);
if(value!=null){
returnvalue;
}else{
returnnull;
}
}
}
ftp.properties
#服务器地址 SERVER_IP=192.168.1.1 #服务器端口 SERVER_PORT=21 #帐号名 USER_NAME=userftp #密码 #PASSWORD=passwordftp
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。