1, How to realize the correspondence between the description and the file when there are multiple file fields in the form?
1. Description and document correspondence
In the file upload page, if there are multiple file fields and multiple corresponding file descriptions,
How do documents and instructions correspond?
We can add the same number to the corresponding file variable and text variable in the form
In the demonstration project, a page for dynamically adding file description and file field is used,
For your reference
2. Precautions for file upload of spring boot:
The spring boot configuration file needs to be modified,
Specify the file size allowed to upload,
Specify the connection timeout to avoid upload timeout when the file is too large
If nginx is used in the access layer, nginx should also be configured accordingly
Description: Liu Hongdi's architecture forest is a blog focusing on architecture. Address: https://www.cnblogs.com/architectforest
The corresponding source code can be obtained here: https://github.com/liuhongdi/
Note: Author: Liu Hongdi email: 371125307@qq.com
2, Presentation project related information
1. Project address:
https://github.com/liuhongdi/fileupload
2. Function Description:
Respectively demonstrated: single file upload,
Multi file upload
Upload when there are multiple file fields in the same form
3. Project structure: as shown in the figure:
3, Profile description
1,application.properties
#thymeleaf spring.thymeleaf.cache=false spring.thymeleaf.encoding=UTF-8 spring.thymeleaf.mode=HTML spring.thymeleaf.prefix=classpath:/templates/ spring.thymeleaf.suffix=.html #upload spring.servlet.multipart.maxFileSize=10MB spring.servlet.multipart.maxRequestSize=30MB #tomcat, server.tomcat.connection-timeout=20000 server.tomcat.max-http-form-post-size=30MB #error server.error.include-stacktrace=always #errorlog logging.level.org.springframework.web=trace
explain:
spring.servlet.multipart.maxFileSize=10MB / / the maximum size of a single file
spring.servlet.multipart.maxRequestSize=30MB / / the maximum size of the uploaded file in the whole form
#tomcat,
server. tomcat. Connection timeout = 20000 / / the connection timeout of Tomcat should not be too short. We use 20 seconds here
server. tomcat. Max HTTP form post size = 30MB / / maximum file size of Tomcat form post
4, java file description
1,FileController.java
@Controller @RequestMapping("/file") public class FileController { //Save path of file private final static String FILE_BASE_PATH = "/data/file/html"; //Multi file domain upload page @GetMapping("/uploadadd") public String uploadAdd(ModelMap modelMap) { return "image/uploadadd"; } //Handle form upload of multiple file fields @PostMapping("/uploadadded") @ResponseBody public RestResult uploadadded(@RequestParam Map<String,String> params,HttpServletRequest request) { RestResult res = new RestResult(); int num = Integer.parseInt(params.get("num")); //Print the name of the file field for debugging Iterator<String> it = ((MultipartHttpServletRequest)request).getFileNames(); while (it.hasNext()) { String uploadFile = it.next(); System.out.println("filename:"+uploadFile); } //Traversal based on the number of file elements in the form for (int i=1;i<=num;i++) { //text String curText = params.get("text"+i); System.out.println("text:"+curText); //file MultipartFile curFile = ((MultipartHttpServletRequest)request).getFile("file"+i); if (curFile.isEmpty()) { continue; } //System.out.println("text:"+curText); String fileName = curFile.getOriginalFilename(); System.out.println("File name: " + fileName); // file extension int lastDot = fileName.lastIndexOf("."); lastDot++; String fileType = fileName.substring(lastDot); // Regenerate a unique file name to store the database String fileSn = UUID.randomUUID().toString(); Map<String, String> map2 = new HashMap<String, String>(); String destFilePath = FILE_BASE_PATH+"/"+fileSn+"."+fileType; File dest = new File(destFilePath); try { curFile.transferTo(dest); } catch (IOException e) { System.out.println("save ioexception"); e.printStackTrace(); } } return res.success(0,"Upload successful"); } //Single file/Multi file upload page @GetMapping("/upload") public String upload(ModelMap modelMap) { return "image/upload"; } //Processing sheet file/Multi file upload @PostMapping("/uploaded") @ResponseBody public RestResult uploaded(HttpServletRequest request) { RestResult res = new RestResult(); List<MultipartFile> list = ((MultipartHttpServletRequest)request).getFiles("files"); for (MultipartFile multipartFile : list) { if (list.isEmpty()) { continue; } // file name String fileName = multipartFile.getOriginalFilename(); System.out.println("File name: " + fileName); // file extension int lastDot = fileName.lastIndexOf("."); lastDot++; String fileType = fileName.substring(lastDot); // Regenerate a unique file name to store the database String fileSn = UUID.randomUUID().toString(); Map<String, String> map2 = new HashMap<String, String>(); String destFilePath = FILE_BASE_PATH+"/"+fileSn+"."+fileType; File dest = new File(destFilePath); try { multipartFile.transferTo(dest); } catch (IOException e) { System.out.println("save ioexception"); e.printStackTrace(); return res.error(0,"Upload failed"); } } return res.success(0,"Upload successful"); } }
Note: when uploading multiple file fields, the file variable and text variable are mainly corresponding
2,RestResult.java
//api General return data public class RestResult<T> { //uuid,Used as a unique identifier to detect consistency during serialization and deserialization private static final long serialVersionUID = 7498483649536881777L; //Identification code, 0 indicates success, and non-0 indicates error private Integer code; //Prompt information is usually used for error reporting private String msg; //Data returned during normal return private T data; //constructor public RestResult() { } //constructor public RestResult(Integer status, String msg, T data) { this.code = status; this.msg = msg; this.data = data; } //Return success data public RestResult success(T data) { return new RestResult(ResponseCode.SUCCESS.getCode(), ResponseCode.SUCCESS.getMsg(), data); } public static RestResult success(Integer code,String msg) { return new RestResult(code, msg, null); } //Return error data public static RestResult error(ResponseCode code) { return new RestResult(code.getCode(), code.getMsg(), null); } public static RestResult error(Integer code,String msg) { return new RestResult(code, msg, null); } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public T getData() { return data; } public void setData(T data) { this.data = data; } }
5, html file description
1,upload.html
<html lang="en"> <head> <script type="text/javascript" language="JavaScript" src="/js/jquery-1.6.2.min.js"></script> </head> <body> <div style="width:100%;height:20px;background:#ffffff;font-size: 16px;" ></div> <div id="content" style="width:800px;"> <div style="width:800px;float:left;"> <!--====================main begin=====================--> <div style="width:260px;height:200px;float:left;background: #eeeeee;padding-left: 10px;padding-top: 10px;"> Single file upload<br/> Note: multiple choices are not allowed<br/> <input id="fileone" type="file" name="fileone" /><br/><br/> <input type="button" name="go" value="Single file upload" onclick="go_single_add()" /> </div> <div style="width:380px;height:200px;float:left;margin-left:20px;background: #eeeeee;padding-left: 10px;padding-top: 10px;"> Multi file upload<br/> Note: multiple choices are allowed<br/> <input id="files" type="file" name="files" multiple /><br/><br/> <input type="button" name="go" value="Multi file upload" onclick="go_multi_add()" /> </div> <!--====================main end=====================--> </div> </div> <script> //Single file upload function go_single_add(){ //Add the file selected in the form to postdata var postdata=new FormData(); if ($("#fileone")[0]==null || $("#fileone")[0].files.length<1){ alert("No picture selected") return false } for (var i=0;i<$("#fileone")[0].files.length;i++){ postdata.append("files",$("#fileone")[0].files[i]) } $.ajax({ type:"POST", url:"/file/uploaded", data:postdata, //Format of returned data datatype: "json",//"xml", "html", "script", "json", "jsonp", "text". processData: false, contentType: false, //Function called after successful return success:function(data){ if (data.code == 0) { alert('Upload successful:'+data.msg); //window.location.href="/image/imagelist"; } else { alert("Upload failed:"+data.msg); } }, //Call the function called after execution complete: function(XMLHttpRequest, textStatus){ }, //Call the function executed in error error: function(XMLHttpRequest, textStatus, errorThrown){ alert(XMLHttpRequest.readyState + XMLHttpRequest.status + XMLHttpRequest.responseText); } }); } //Multi file upload function go_multi_add(){ //Add the file selected in the form to postdata var postdata=new FormData(); if ($("#files")[0]==null || $("#files")[0].files.length<1){ alert("No picture selected") return false } for (var i=0;i<$("#files")[0].files.length;i++){ postdata.append("files",$("#files")[0].files[i]) } $.ajax({ type:"POST", url:"/file/uploaded", data:postdata, //Format of returned data datatype: "json",//"xml", "html", "script", "json", "jsonp", "text". processData: false, contentType: false, //Function called after successful return success:function(data){ if (data.code == 0) { alert('Upload successful:'+data.msg); //window.location.href="/image/imagelist"; } else { alert("Upload failed:"+data.msg); } }, //Call the function called after execution complete: function(XMLHttpRequest, textStatus){ }, //Call the function executed in error error: function(XMLHttpRequest, textStatus, errorThrown){ alert(XMLHttpRequest.readyState + XMLHttpRequest.status + XMLHttpRequest.responseText); } }); } </script> </body> </html>
This page shows both single file upload and multi file upload
2,uploadadd.html
<html lang="en"> <head> <script type="text/javascript" language="JavaScript" src="/js/jquery-1.6.2.min.js"></script> </head> <body> <div style="width:100%;height:20px;background:#ffffff;font-size: 16px;" ></div> <div id="content" style="width:800px;"> <div style="width:800px;float:left;"> <!--====================main begin=====================--> <div style="width:280px;float:left;background: #eeeeee;padding-left: 10px;padding-top: 10px;"> Single file upload<br/> Note: multiple choices are not allowed<br/> <form id="form_add" method="POST" action="" enctype="multipart/form-data"> <div id="filelist" style="width: 260px;"> <div style="width:260px;height:50px;background: #ffff00;padding:2px 5px;"> <input type="text" style="width:200px;" name="text1" placeholder="Document description"/><br/> <input id="file1" type="file" name="file1" /> </div> </div> </form> <input type="button" name="gofile" value="Append file" onclick="go_add()" /><br/><br/> <input type="button" name="goupload" value="Submit" onclick="go_commit()" /> </div> <!--====================main end=====================--> </div> </div> <script> //Maximum number of uploaded files var global_file_max = 10; //In the current form file quantity var global_file_num = 1; //Submit a form with dynamically generated elements function go_commit() { var postdata = new FormData($("#form_add")[0]); //Number of form elements attached to the file postdata.append("num",global_file_num); $.ajax({ type:"POST", url:"/file/uploadadded", data:postdata, //Format of returned data datatype: "json",//"xml", "html", "script", "json", "jsonp", "text". processData: false, contentType: false, //Function called after successful return success:function(data){ if (data.code == 0) { alert("success:"+data.msg); } else { alert("failed:"+data.msg); } }, //Call the function called after execution complete: function(XMLHttpRequest, textStatus){ }, //Call the function executed in error error: function(XMLHttpRequest, textStatus, errorThrown){ alert(XMLHttpRequest.readyState + XMLHttpRequest.status + XMLHttpRequest.responseText); } }); } //Add a file form element function go_add() { var divcss = { "background-color": "#ff0000", "width":"260px", "height":"50px", "padding":"2px 5px" }; if (global_file_num>=global_file_max) { alert('The number of uploaded files has been exceeded'); return false; } global_file_num++; var parentdiv=$('<div></div>'); //Create a div parentdiv.attr('id','filediv'+global_file_num); parentdiv.css(divcss); //add to css style var divhtml = '<input type="text" style="width:200px;" name="text'+global_file_num+'" placeholder="Document description"/><br/>' + '<input id="file'+global_file_num+'" type="file" name="file'+global_file_num+'" />'; parentdiv.html(divhtml); $("#filelist").append(parentdiv); } </script> </body> </html>
Demonstrates the dynamic addition of file elements and text elements with jquery
6, Test effect
1. Visit:
http://127.0.0.1:8080/file/upload
Test single file upload and multi file upload respectively:
To view uploaded files in the file manager:
2. Upload of multiple file fields in the test form:
visit:
http://127.0.0.1:8080/file/uploadadd
Click append file to add two files
After the test is submitted, view the console:
filename:file1
filename:file2
filename:file3
text:aaaa
File name: qtz.jpg
text:bbbb
File name: qtz2.jpeg
text:ccc
File name: yellowbee.jpeg
text has no corresponding file name and description
7, View the version of spring boot
. ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ :: Spring Boot :: (v2.3.2.RELEASE)