Sample code for SpringMVC file upload and view
- 2020-12-20 03:34:34
- OfStack
Writing in the front
When it comes to file upload, first of all, to say the business logic, if uploaded files you can see (such as advertising or homepage banner), etc., then we will put the pictures in a static resource area (location) and css js1 sample, if the file is protected (like a user can only view your upload photos), then we will make it a special store the location of the image that is stored in the server.
This example shows how to upload files in both locations. After uploading, as an extension, it also adds the ability to view the uploaded files and download the uploaded files.
The preparatory work
Configure SpringMVC to import the commons package
In ES18en-ES19en. xml, the configuration file uploads the parser
<!-- File upload parser -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1000000"/>
<property name="defaultEncoding" value="UTF-8" />
</bean>
It is stored in the static resource area
1. Storage Location:
Is stored in the project, so the path is the path of the relative project.
/{yourproject}/webapp/static/img
2. Configure handler for the response
@Controller
public 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/";
// Gets the source file name uploaded by the user
String fileName = file.getOriginalFileName();
// The new file
File file1 = new File(path, fileName);
// Write the file
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 server
1. Storage location of this example:
It is stored somewhere on the server, independent of the project, so the address is the absolute path.
/ Users/mac/Desktop/imgtemp, absolute path to the directory.
2. Configure handler for the response
...
@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();
// Gets the save file folder path
String path = "/Users/mac/Desktop/imgtemp/";
// The new file
File file1 = new File(path,fileName);
// Written to the file
file.transferTo(file1);
}
}
...
Extension (Viewing and downloading of documents)
Since the response is to transfer files in the form of flow, we need the correct browser setting response MIMIE types can be correct parsing, the default MIMIE application file types for application/octet - stream, MIME set to this value, the browser will not automatically perform or ask the class files, to treat the form of attachment to download files directly to the local.
See this post for more on MIMIE
If we want to customize the name of the download file, we need to set the ES71en-ES72en message.
The ES74en-ES75en header indicates how the content of the reply should be displayed, inline (that is, a web page or part 1 of a page), or downloaded and saved locally as an attachment.
For more on Content-ES79en, check out 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;
}
// The path to the file
String path = "/Users/mac/Desktop/imgtemp/";
// The new file
File file = new File(path,fileName);
if(!file.exists()) {
response.sendError(404);
return;
}
// If the request parameter saveName Don't empty , Download the file
if(!StringUtils.isEmpty(saveName)) {
// Set the response length
response.setContentLength((int)file.length());
// Set responsive MIME A type of application/octet-stream
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
saveName = new String(saveName.getBytes("UTF-8"),"ISO8859-1");
// Set up the content-disposition for attachment;fileName=saveName
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+saveName+"\"");
}
// Read the file
InputStream is = new FileInputStream(file);
OutputStream os = response.getOutputStream();
// Output the file as a stream
IOUtils.copy(is,os);
os.flush();
os.close();
is.close();
}
We can also output the file using the ByteArrayHttpMessageConverter converter that comes with SpringMVC, which implements the HttpMessageConverter interface. All MIME request messages can be read, and the MIME for the response messages is application/ ES89en-ES90en
...
@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 class="container">
<h1 class="text-center"> Upload file sprinkle </h1>
<c:if test="${not empty message}">
<h2>${message}</h2>
</c:if>
<form:form enctype="multipart/form-data" action="/upload/static">
<p class="text-info"> Uploaded to the /web/static</p>
<label for=""> Upload a file :</label>
<input type="file" name="uploadFile">
<button class="btn btn-default"> submit </button>
</form:form>
<form:form enctype="multipart/form-data" action="/upload/disk">
<p class="text-info"> Uploaded to the Disk</p>
<label for=""> Upload a file </label>
<input type="file" name="uploadFile">
<button class="btn btn-default"> submit </button>
</form:form>
<div class="container">
<button class="btn btn-default">
<a href="/download/byDefault?fileName=dubbo.png" rel="external nofollow" target="_blank"> View uploads to by default Disk the dubbo The picture </a>
</button>
<button class="btn btn-default">
<a href="/download/byDefault?fileName=dubbo.png&saveName=dubb.png" rel="external nofollow" > Use the default download mode dubbo The picture </a>
</button>
</div>
<div class="container">
<button class="btn btn-default">
<a href="/download/byConvert?fileName=dubbo.png" rel="external nofollow" target="_blank"> use MVC Converter view upload to Disk the dubbo The picture </a>
</button>
<button class="btn btn-default">
<a href="/download/byConvert?fileName=dubbo.png&saveName=dub.png" rel="external nofollow" > use MVC Converter download and upload to Disk the dubbo The picture </a>
</button>
</div>
</div>
</body>
</html>