详解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.multipart.commons.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 = multipartrequest.getfile("file");//file是页面input的name名 string basepath = "文件路径" try { multipartresolver resolver = new commonsmultipartresolver(request.getsession().getservletcontext()); if (resolver.ismultipart(request)) { string filestoredpath = "文件夹路径"; //随机生成文件名 string randomname = stringutil.getrandomfilename(); string uploadfilename = file.getoriginalfilename(); 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 = savefile.getparentfile(); if (savefile.exists()) { savefile.delete(); } else { if (!parentfile.exists()) { parentfile.mkdirs(); } } //复制文件到指定路径 fileutils.copyinputstreamtofile(file.getinputstream(), savefile); //上传文件到服务器 ftpclientutil.upload(savefile, filestoredpath); } } } catch (exception e) { e.printstacktrace(); } }
ftp客户端上传工具
package com.yuanding.common.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.net.socketexception; import java.util.hashmap; import java.util.map; import java.util.properties; import org.apache.commons.lang.stringutils; import org.apache.commons.net.ftp.ftp; import org.apache.commons.net.ftp.ftpclient; import org.apache.commons.net.ftp.ftpreply; import org.slf4j.logger; import org.slf4j.loggerfactory; /** * ftp客户端工具 */ public class ftpclientutil { /** * 日志 */ private static final logger logger = loggerfactory.getlogger(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 directory * 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 = ftpclientutil.class.getresourceasstream("/ftp.properties"); prop.load(fps); fps.close(); } catch (exception e) { 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)); } /** * 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 (!filetoupload.exists()) { throw new illegalargumentexception("file to upload does not exists:" + filetoupload.getabsolutepath ()); } if (!filetoupload.isfile()) { throw new illegalargumentexception("file to upload is not a file:" + filetoupload.getabsolutepath()); } if (stringutils.isblank((string) servercfg.get(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) servercfg.get(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) servercfg.get(server_ip); integer port = (integer) servercfg.get(server_port); boolean isanonymous = (boolean) servercfg.get(is_anonymous); string username = (string) servercfg.get(user_name); string password = (string) servercfg.get(password); boolean ispasv = (boolean) servercfg.get(is_pasv); string workingdirectory = (string) servercfg.get(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); ftpclient.connect(host); } else { logger.debug("connect to ftp server on " + host + ":" + port); ftpclient.connect(host, port); } int reply = ftpclient.getreplycode(); if (!ftpreply.ispositivecompletion(reply)) { logger.error("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)) { logger.error("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."); ftpclient.enterlocalpassivemode(); } else { logger.debug("use the active mode to transfer file."); ftpclient.enterlocalactivemode(); } if (stringutils.isblank(workingdirectory)) { workingdirectory = "/"; } logger.debug("change current working directory to " + workingdirectory); changeworkingdirectory(ftpclient,workingdirectory); if (isupload) { // upload if (stringutils.isblank(serverfilestoredname)) { serverfilestoredname = filetoupload.getname(); } filein = new fileinputstream(filetoupload); logger.debug("upload file : " + filetoupload.getabsolutepath() + " to ftp server with name : " + serverfilestoredname); if (!ftpclient.storefile(serverfilestoredname, filein)) { logger.error("fail to upload file, " + ftpclient.getreplystring()); } else { logger.debug("success to upload file."); } } else { // download // make sure the file directory exists file filestored = new file(localfilestoredpath); if (!filestored.getparentfile().exists()) { filestored.getparentfile().mkdirs(); } fileout = new fileoutputstream(filestored); logger.debug("download file : " + filenametodownload + " from ftp server to local : " + localfilestoredpath); if (!ftpclient.retrievefile(filenametodownload, fileout)) { logger.error("fail to download file, " + ftpclient.getreplystring()); } else { logger.debug("success to download file."); } } ftpclient.noop(); 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) { } } } } private static final boolean changeworkingdirectory(ftpclient ftpclient, string workingdirectory) throws ioexception{ if(!ftpclient.changeworkingdirectory(workingdirectory)){ string [] paths = workingdirectory.split("/"); for(int i=0 ;i<paths.length ;i++){ if(!"".equals(paths[i])){ if(!ftpclient.changeworkingdirectory(paths[i])){ ftpclient.makedirectory(paths[i]); ftpclient.changeworkingdirectory(paths[i]); } } } } return true; } public static final void upload(map<string, object> servercfg, string filepathtoupload, string filestoredpath, string filestoredname) throws socketexception, ioexception { upload(servercfg, new file(filepathtoupload), filestoredpath, filestoredname); } public static final void upload(map<string, object> servercfg, file filetoupload, string filestoredpath, string filestoredname) throws socketexception, ioexception { if(filestoredpath!=null && !"".equals(filestoredpath)){ servercfg.put(working_directory, filestoredpath); } upload(servercfg, filetoupload, filestoredname); } public static final void upload(string filepathtoupload, string filestoredpath)throws socketexception, ioexception { upload(servercfg, filepathtoupload, filestoredpath, ""); } public static final void upload(file filetoupload, string filestoredpath)throws socketexception, ioexception { upload(servercfg, filetoupload, filestoredpath, ""); } public static string values(string key) { string value = prop.getproperty(key); if (value != null) { return value; } else { return null; } } }
ftp.properties
#服务器地址 server_ip=192.168.1.1 #服务器端口 server_port=21 #帐号名 user_name=userftp #密码 #password=passwordftp
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。
推荐阅读