Write in front
When it comes to file uploads, we must first talk about business logic. If everyone can see the uploaded files (such as advertisements or banners on the homepage), then we put the image in the static resource area (the same location as css and js). If the file is protected (such as the user can only view the photos uploaded by himself), then we store it in a location on the server where the pictures are specially stored.
This example shows the method of uploading files stored in two locations. After uploading, as an extension, the function of viewing uploaded files and downloading uploaded files is also added.
Preparation
Configure SpringMVC and import commons packages
Configure file upload parser in mvc-servlet.xml
<!--File Upload Parser--> <bean id="multipartResolver" > <property name="maxUploadSize" value="1000000"/> <property name="defaultEncoding" value="UTF-8" /> </bean>
Stored in static resource areas
1. Storage location:
Stored in the project, so the path is the path relative to the project.
/{yourproject}/webapp/static/img
2. Configure the responding handler
@Controllerpublic class UploadController { @GetMapping("/upload") public String UploadHandler() { return "upload"; } @PostMapping("/upload/static") public void wriToStatic(HttpServletRequest request, RedirectAttributes redirectAttributes, @RequestParam("fileName") MultipartFile file) { if(!file.isEmpty()) { //Get the target folder String path = request.getServletContext().getRealPath("/") + "static/img/"; //Get the source file name uploaded by the user String fileName = file.getOriginalFileName(); //Create a new file File file1 = new File(path, fileName); //Write the file to file.transferTo(file1); redirectAttributes.addFlashAttribute("message","upload to static success"); return "redirect:/upload"; } else { redirectAttributes.addFlashAttribute("message","upload file can not be empty"); return "redirect:/upload"; } }}Store on the server
1. Storage location of this example:
Stored at a certain location on the server, has nothing to do with the project, so the address is an absolute path.
/Users/mac/Desktop/imgtemp/, is the absolute path to the directory.
2. Configure the responding handler
...@PostMapping("/upload/disk")public String writeToDisk(HttpServletRequest request, @RequestParam("fileName") MultipartFile file, RedirectAttributes redirectAttributes) { if(!file.isEmpty()) { //Get the source file name String fileName = file.getOriginalFileName(); //Get the save file folder path String path = "/Users/mac/Desktop/imgtemp/"; //Create a new file File file1 = new File(path,fileName); //Write file file.transferTo(file1); }}...Extended part (view and download of files)
Since the response is to pass the file in the form of a stream, we need to correctly set the MIMIE type of the response to be correctly parsed by the browser. The default MIMIE type of the application file is application/octet-stream. After MIME is set to this value, the browser will not automatically execute or ask to execute such files, and will directly download the file to the local area in the form of treating attachments.
For more interpretations of MIMIE, please check this article
If we want to customize the name of the download file, we need to set the Content-Disposition message.
Content-Disposition The message header indicates the form of the reply to be displayed, whether it is inline (i.e., a web page or part of a page), or downloaded and saved locally in the form of an attachment.
For more information about Content-Disposition, please check this article
...@GetMapping("/download/byDefault")public void getImgByDefault(@RequestParam String fileName, @RequestParam(required=false,defaultValue="") String saveName), HttpServletResponse response { if(StringUtils.isEmpty(fileName)) { response.sendError(404); return; } //Path of file storage String path = "/Users/mac/Desktop/imgtemp/"; //New file File file = new File(path,fileName); if(!file.exists()) { response.sendError(404); return; } //If the request parameter saveName is not empty, download the file if(!StringUtils.isEmpty(saveName)) { //Set the response length response.setContentLength((int)file.length()); //Set the MIME type of the response to application/octet-stream response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); saveName = new String(saveName.getBytes("UTF-8"),"ISO8859-1"); //Set content-disposition to attachment; fileName=saveName response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=/""+saveName+"/""); } //Read the file InputStream is = new FileInputStream(file); OutputStream os = response.getOutputStream(); //Output file IOUtils.copy(is,os); os.flush(); os.close(); is.close();}We can also use the ByteArrayHttpMessageConverter converter that comes with SpringMVC to output files, which implements the HttpMessageConverter interface. All MIME request information can be read, and the MIME of the response information is application/octet-stream
...@GetMapping("/download/byConvert")public HttpEntity<byte[]> getImgByConvert(@RequestParam String fileName, @RequestParam(required=false,defaultValue="") String saveName) { if(StringUtils.isEmpty(fileName)) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } String path = "/Users/mac/Desktop/imgtemp/"; File file = new File(path,fileName); if(!file.exists()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } HttpHeaders headers = new HttpHeaders(); if(!StringUtils.isEmpty(saveName)) { headers.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); headers.setContentLength(file.length()); saveName = new Sting(saveName.getBytes("UTF-8"),"ISO8859-1"); headers.add(HttpHeaders.CONTENT_DISPOSITION,"attachment;fileName=/"" + saveName + "/""); } else { headers.setContentType(MediaType.IMAGE_PNG); } return new HttpEntity<>(FileCopyUtils.copyToByteArray(file),headers);}upload.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %><%@taglib prefix="form" uri="http://www.springframework.org/tags/form" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!doctype html><html><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="/static/bootstrap-3.3.5-dist/css/bootstrap.css" rel="external nofollow" ></head><body><div> <h1>Upload file scatter</h1> <c:if test="${not empty message}"> <h2>${message}</h2> </c:if> <form:form enctype="multipart/form-data" action="/upload/static"> <p>Upload to /web/static</p> <label for="">Upload file:</label> <input type="file" name="uploadFile"> <button>Submit</button> </form:form> <form:form enctype="multipart/form-data" action="/upload/disk"> <p>Upload to Disk</p> <label for="">Upload file</label> <input type="file" name="uploadFile"> <button>Submit</button> </form:form> <div> <a href="/download/byDefault?fileName=dubbo.png" rel="external nofollow" target="_blank">Use the default method to view dubbo images uploaded to Disk</a> </button> <button> <a href="/download/byDefault?fileName=dubbo.png&saveName=dubb.png" rel="external nofollow" >Use the default method to download dubbo images</a> </button> </div> <div> <button> <a href="/download/byConvert?fileName=dubbo.png" rel="external nofollow" >Use the default method to download dubbo images</a> </button> </div> <div> <button> <a href="/download/byConvert?fileName=dubbo.png" rel="external nofollow" target="_blank">Use MVC converter to view dubbo images uploaded to Disk</a> </button> <button> <a href="/download/byConvert?fileName=dubbo.png&saveName=dub.png" rel="external nofollow" >Use MVC converter to download dubbo images uploaded to Disk</a> </button> </div></div></body></html>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.