Springmvc implements file uploads
A page.
var disBill=0;
functionuploadFileContract(formId, selectedFile, businessTable, billId, modelName) { billId = disBill; // Get the uploaded file ID // represent the import declaration modelName ="CustomsDeclareBill";
logisticsUploadFile(formId, selectedFile, businessTable, billId, modelName);
}
function logisticsUploadFile(formId, selectedFile, businessTable, billId, modelName) {
$Form = $("#"+ formId); STR = $(The '#' + selectedFile).val();
var fileType;
if (str == ' ') {
callAlert('Please select the file to upload first');
}
if(! (/ (? :jpg|png|txt|xls|pdf|xlsx|doc|docx|rar|zip|html)$/i.test(str))) { callAlert("Upload file type illegal!");
return;
}
else {
if((/ (? :jpg)$/i.test(str))){fileType='jpg'}
if((/ (? :png)$/i.test(str))){fileType='png'}
if((/ (? :txt)$/i.test(str))){fileType='txt'}
if((/ (? :xls)$/i.test(str))){fileType='xls'}
if((/ (? :doc)$/i.test(str))){fileType='doc'}
if((/ (? :docx)$/i.test(str))){fileType='docx'}
if((/ (? :rar)$/i.test(str))){fileType='rar'}
if((/ (? :zip)$/i.test(str))){fileType='zip'}
if((/ (? :xlsx)$/i.test(str))){fileType='xlsx'}
if((/ (? :pdf)$/i.test(str))){fileType='pdf'}
if((/ (? :html)$/i.test(str))){fileType='html'}
var arr = str.split('\ \'); Var fileName = arr[arr.leng-1]; FileName = encodeURI(encodeURI(fileName)); // fileType = encodeURI(encodeURI(fileType)); var BillId=$("#billIdRecord").val();
var formURL = getContextPath() + 'customsDeclareBill/upload.do? BillId='+BillId+'&fileType='+fileType+'&modelName='+modelName;
var form = document.getElementById(formId);
var formData = new FormData(form);
$.ajax({
url: formURL,
type: 'POST',
data: formData,
mimeType: "multipart/form-data",
contentType: false,
cache: false,
processData: false,
success: function (res) {
callSuccess("Success!!!!!");
customsGoods_table.ajax.reload();
customsGoods_table2.ajax.reload();
$('#importBillModal').modal('hide');
},
error: function () {
callSuccess("Failure!!"); customsGoods_table.ajax.reload(); customsGoods_table2.ajax.reload(); }}}})Copy the code
Controller Controller
@RequestMapping(value = "/upload.do". method = { RequestMethod.POST }) public @ResponseBody Object upload(HttpServletRequest request) throws IllegalStateException, IOException, FileUploadException { RequestResultVO rr = new RequestResultVO(); CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); // Determine if there are multiple file uploads, i.e. multiple requestsif(multipartResolver isMultipart (request)) {try {/ / into a part of the request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; / / multiple file filename Iterator iter. = multiRequest getFileNames ();whileF = multirequest.getFile (iter. Next().tostring ()));if(f ! String fileName = f.getOriginalfilename (); Long fileSize = f.getSize(); String fileType = request.getParameter("fileType"); // Get the file typeif(fileName.trim() ! ="") {
String modelName=request.getParameter("modelName");
//String basepath = filepath+File.separator+modelName+File.separator+DateUtil.format(new Date(), "yyyyMMdd")+File.separator;
String basepath=servletContext.getRealPath("/").substring(0, servletContext.getRealPath("/").lastIndexOf("SeawinWebappBase")) +"/seawin-uploadfile/"+modelName+"/"; FileUtil.mkDirs(basepath); String newFileName = uuid.randomuuid ().toString().replace()"-"."") +"."+FilenameUtils.getExtension(fileName);
File localFile = new File(basepath+File.separator+ fileName);
int i = 1;
newFileName = fileName;
while(localFile.exists()){
if(fileName.indexOf(".") != -1){
newFileName = fileName.substring(0, fileName.indexOf(".")) +"-"+i+fileName.substring(fileName.indexOf("."));
}else{
newFileName = fileName +"-"+i;
}
i++;
localFile = new File(basepath+File.separator+newFileName);
}
f.transferTo(localFile); String outPath=request.getScheme()+ String outPath=request.getScheme()+": / /"+request.getServerName()+":"+request.getServerPort(); // The name of the folder to upload the file: folder name + module name + file name String fileUrl=outPath +"/seawin-uploadfile/"+modelName+"/"+ newFileName;
String message = ""; // 0 indicates that the upload is successful, and 1 indicates that the upload failsif(! f.isEmpty() && f ! = null) { message ="0";
} else {
message = "1";
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
rr.setContent(1, "Upload failed", null);
returnrr; }}return rr;
}Copy the code
Springmvc configuration for uploading files
<? xml version="1.0" encoding="UTF-8"? > <beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:cache="http://www.springframework.org/schema/cache" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:websocket="http://www.springframework.org/schema/websocket"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache.xsd"> <! --> <context:component-scan base-package="com.seawin.webapp.base.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.sale.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.base.mobileweb" />
<context:component-scan base-package="com.seawin.webapp.freight.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.customs.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.workflow.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.shipping.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.air.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.logistics.controller.pcweb" />
<context:component-scan base-package="com.seawin.webapp.account.controller.pcweb"/ > <! -- View parser --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView" p:prefix="/"
p:suffix=".html"/ > <! -- Annotation --> <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"> </bean> <! - the json converter RequestMappingHandlerAdapter - > < bean class ="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean
class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes"> <list> <value>text/html; charset=UTF-8</value> <value>application/json; charset=UTF-8</value> <value>text/plain; charset=UTF-8</value> </list> </property> </bean> <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes"> <list> <value>text/html; charset=UTF-8</value> <value>application/json; charset=UTF-8</value> <value>text/plain; charset=UTF-8</value> </list> </property> </bean> </list> </property> </bean> <bean id="multipartResolver" class="com.seawin.webapp.base.mulipart.MyMultipartResolver"> <! HTTP requests with excludeUrls in the URL are not parsed by multipartResolver --> <! -- All manually configured interfaces for uploading files --> <property name="excludeUrls"
value="/uploader/uploadFile.do,/saleFile/uploader.do, /freightAttachment/uploadFile.do,/user/uploader.do, /logisticsAttachment/uploader.do,/CustomsDeclareBill/upload.do,/ShippingBill/upload.do"/ > <! -- Maximum number of uploaded files --> <property name="maxUploadSize" value="104857600"></property> <! -- Upload file encoding --> <property name="defaultEncoding" value="utf-8"></property> </bean> <! Static file mapping --> < MVC: Resources location="/" mapping="/**/*.html" />
<mvc:resources location="/" mapping="/**/*.js" />
<mvc:resources location="/" mapping="/**/*.css" />
<mvc:resources location="/" mapping="/**/*.png" />
<mvc:resources location="/" mapping="/**/*.gif"/ > <! -- File upload --> <! -- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> set the maximum size of the uploaded file to 5MB <property name="maxUploadSize"> <value>5242880</value> </property>
</bean> -->
</beans>Copy the code
MultipartFile class MultipartFile
String getContentType()// Get the file MIME type InputStream getInputStream()// Get the file stream String getName() // Get the name of the file component in the form String GetOriginalFilename () // obtain the original name of the uploaded File long getSize() // obtain the size of the File in bytes Boolean isEmpty() // whether the File isEmpty void transferTo(File dest)Copy the code
5: CommonsMultipartResolver attribute resolution
DefaultEncoding: indicates the defaultEncoding used to resolve request requests. If not specified, the default iso-8859-1 is used according to the Servlet specification. DefaultEncoding is ignored when the request specifies its encoding format. UploadTempDir: Sets the temporary directory for uploading files. Default is the temporary directory of the Servlet container. MaxUploadSize: Sets the maximum file size, in bytes, that can be uploaded. If the value is set to -1, there is no limit. The default value is -1. MaxUploadSizePerFile: similar to maxUploadSize, except that maxUploadSizePerFile limits the size of each uploaded file, while maxUploadSizePerFile limits the total uploaded file size. MaxInMemorySize: Sets the maximum number of bytes that can be written to memory during file upload. The default value is 10240. ResolveLazily:true, enable deferred file resolution to catch file size exceptions in UploadAction.Copy the code
1. Sometimes uploading errors occur because we have set a limit on the size of uploaded files in the configuration file. You can do without this limit, but I suggest you add this limit. 2.SpringMVC uses MultipartFile to receive uploaded files. Two JARS are required: commons-fileupload-1.3.3.jar and commons-io-2.5.jar.