Implementation of Upload and Download Function of SpringBoot File or Picture
- 2021-08-28 20:12:13
- OfStack
Import dependencies (pom. xml)
<!-- Upload and download to be designed jar Bag -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api Import a higher version of -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!-- Picture processing class -->
<dependency>
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
Global configuration application. properties
# Upload file size
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
Creating WebMvcConfig Configuration Class Static Resource Mapping
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
ApplicationHome h = new ApplicationHome(getClass());
File jarF = h.getSource();
String dirPath = jarF.getParentFile().toString()+"/upload/";
String os = System.getProperty("os.name");
if (os.toLowerCase().startsWith("win")) { // If it is Windows System
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
} else {
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
}
}
}
Upload files or pictures
Control layer
// Upload a file
@ResponseBody
@RequestMapping("/upload")
public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException {
// // win System Upload path save settings
// // Get Project Path
// File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
// // Absolute path = Project path + Custom path
// File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/");
// if (!pathFile.exists()) {
// pathFile.mkdirs();
// }
// // Upload file address
// UUID uuid = UUID.randomUUID();
// File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
// files.transferTo(serverFile);
//
// String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
//
// return imgPath;
// Linux Server Upload path save settings
// Project path /home/www/
File pathFile = new File("/home/www/upload/");
if (!pathFile.exists()) {
pathFile.mkdirs();
}
// Upload file address
UUID uuid = UUID.randomUUID();
File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
files.transferTo(serverFile);
String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
return imgPath;
}
HTML page
Ajax Upload without Refresh
<form action="" class="layui-form" enctype="multipart/form-data" method="post">
<input type="hidden" name="blogImg" id="imgPath" value="">
<div class="form-group">
<label> Picture upload </label>
<input type='file' style='margin: 5px;' name='files' required><br>
<button type="button" class="layui-btn" id="img_upload"> Upload pictures </button>
</div>
<input type="submit">
</form>
JS
// Ordinary picture upload
$('#img_upload').click(function () {
var formData = new FormData();
// Get the selected file
$.each($('input[name="files"]'),function (index,item) {
formData.append("files",item.files[0])
});
// Send an asynchronous request
$.ajax({
method:'post',
url: '[[@{/user/upload}]]', // File upload interface
data:formData,
processData: false,
contentType:false,
success:function (data) {
// Successfully returned the triggered method
$('#imgPath').val(data);
alert(" Upload succeeded ");
},
// Method triggered by request failure
error:function () {
alert(" Upload failed ");
}
});
});
File or Picture Download
Control layer
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
// The address of the picture to download
String path = request.getServletContext().getRealPath("/upload");
String fileName = " Basic grammar .jpg";
//1 , setting response Response header
response.reset(); // Setting the page not to cache , Empty buffer
response.setCharacterEncoding("UTF-8"); // Character encoding
response.setContentType("multipart/form-data"); //2 Binary transmission data
// Set the response header
response.setHeader("Content-Disposition",
"attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));
File file = new File(path,fileName);
//2 , Read a file -- Input stream
InputStream input=new FileInputStream(file);
//3 , Write out a document -- Output stream
OutputStream out = response.getOutputStream();
byte[] buff =new byte[1024];
int index=0;
//4 , execution Write out operation
while((index= input.read(buff))!= -1){
out.write(buff, 0, index);
out.flush();
}
out.close();
input.close();
return null;
}
HTML page
<a href="/download" rel="external nofollow" > Click to download </a>
SpringBoot files or pictures can be uploaded and downloaded