Detailed explanation of the realization of file uploading and downloading under SpringBoot
- 2021-07-26 07:43:12
- OfStack
How to upload and download files in SpringBoot background?
A recent project involves uploading and downloading files. Baidu webUploader plug-in is used for front-end uploading. The usage of this plug-in is still under study, which will be sorted out and recorded in the future. This paper mainly introduces the processing of file uploading and downloading in SpringBoot background.
Single file upload
/ Single file upload
@RequestMapping(value = "/upload")
@ResponseBody
public String upload(@RequestParam("file") MultipartFile file) {
try {
if (file.isEmpty()) {
return " File is empty ";
}
// Get the file name
String fileName = file.getOriginalFilename();
logger.info(" The uploaded file name is: " + fileName);
// Gets the suffix name of the file
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info(" The suffix of the file is: " + suffixName);
// Set the file storage path
String filePath = "D://aim//";
String path = filePath + fileName + suffixName;
File dest = new File(path);
// Detect if a directory exists
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();// New Folder
}
file.transferTo(dest);// File writing
return " Upload succeeded ";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return " Upload failed ";
}
If you want to modify the file path and file name, modify filePath and fileName.
Multiple file upload
/ Multiple file upload
@RequestMapping(value = "/uploadMore", method = RequestMethod.POST)
@ResponseBody
public String handleFileUpload(HttpServletRequest request) {
List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file");
MultipartFile file = null;
BufferedOutputStream stream = null;
for (int i = 0; i < files.size(); ++i) {
file = files.get(i);
String filePath = "D://aim//";
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
stream = new BufferedOutputStream(new FileOutputStream(
new File(filePath + file.getOriginalFilename())));// Set the file path and name
stream.write(bytes);// Write
stream.close();
} catch (Exception e) {
stream = null;
return " No. 1 " + i + " Failed to upload files ==> "
+ e.getMessage();
}
} else {
return " No. 1 " + i
+ " Failed to upload files because the file is empty ";
}
}
return " Upload succeeded ";
}
File download
// File download related code
@RequestMapping("/download")
public String downloadFile(HttpServletRequest request, HttpServletResponse response) {
String fileName = "aim_test.txt";// Set the file name and replace it with the file name to be downloaded according to business needs
if (fileName != null) {
// Set the file path
String realPath = "D://aim//"
File file = new File(realPath , fileName);
if (file.exists()) {
response.setContentType("application/force-download");// Setting Force Download Not Open
response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// Set the file name
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("success");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
return null;
}
MultipartConfig Configuration
File uploads can be controlled globally through the MultipartConfig configuration class.
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
// Set file size limit , Pages beyond this size will throw exception information
factory.setMaxFileSize("2MB"); //KB,MB
// Set the total uploaded data size
factory.setMaxRequestSize("20MB");
// Set the file temporary folder path
// factory.setLocation("E://test//");
// If the file is greater than this value, it will be stored as a file. If it is less than this value, the file will be stored in memory, and the default is 0
// factory.setMaxRequestSize(0);
return factory.createMultipartConfig();
}
}
Matters needing attention
The front and back end file transfer format should be multipart/form-data