1. Overview
MultipartFile is a class under the package. That is to say, if you want to use the MultipartFile class, you must introduce the spring framework. In other words, if you want to use the MultipartFile class in your project, then the project must use the spring framework, otherwise this class cannot be introduced.
When translated into Chinese, MultipartFile is "multi-component document". You don't have to care too much about its Chinese meaning. Generally speaking, using the MultipartFile class is mainly used to implement the file upload function in the form of a form.
2. Methods in MultipartFile
getName method
The getName method obtains the name of the parameter passed in file agreed by the front and back end.
getOriginalFileName method
The getOriginalFileName method obtains the complete name of the file, including the file name + the file extension name.
getContentType method
The getContentType method gets the file type, note that it is the file type, not the file extension name.
isEmpty method
The isEmpty method is used to determine whether the passed file is empty. If it is empty, it means that no file is passed in.
getSize method
The getSize method is used to get the size of the file, in bytes.
getBytes method
The getBytes method is used to convert a file into a byte array for transmission, and will throw an IOException exception.
getInputStream method
The getInputStream method is used to convert the file into an input stream to transfer the file, and will throw an IOException exception.
transferTo method
The transferTo method is used to transfer the received file to the given target path
3. Some tips for using MultipartFile
- (1) When we use MultipartFile as a parameter, we can declare MultipartFile as an array, which can support multiple file transfers. If we only need to transfer one file, just remove the array.
- (2) The size of the transferred file can be obtained according to the getSize method of MultipartFile, so that the size of the transferred file can be limited.
4. Upload code display
- Business logic code:
package ; import ; import ; import .slf4j.Slf4j; import ; import ; import ; import ; import ; import ; import ; import ; import ; @Slf4j @RestController @RequestMapping("/file") public class FileUploadController { /** * Upload file * 1. Determine whether the file is empty * 2. Get the file name, file type, file size (you can limit the file type and file size) * 3. Set the file upload path * 4. Output the file in a stream * 5. Return to upload successfully * @param file * @return * @throws Exception */ @PostMapping("/upload") public String uploadImage(@RequestParam("file") MultipartFile file) throws Exception{ // Determine whether the file is empty if (()) { return "Upload failed"; } //The file type is String contentType = (); ("File type is:" + contentType); if (("image/jpeg")){ return "Please upload the correct formatted file"; } // Get the original file name String fileName = (); ("The uploaded file name is:" + fileName); try { // Save the file to the specified location byte[] bytes = (); ("File size is:" + ); // TODO: Choose the appropriate storage method according to business needs, such as saving to local disk or cloud storage// Get the generated file name String s = (fileName); // Save the file to the specified location (file,"C:\\Users\\liguoming\\Desktop",s); return "Uploaded successfully"; } catch (Exception e) { (); return "Upload failed"; } } }
- FlieUtils tool class:
package ; import .slf4j.Slf4j; import ; import ; import ; @Slf4j public class FlieUtils { /** * @param file * @param fileName New random filename */ public static void upload(MultipartFile file, String destPath, String fileName) { File dest = new File(destPath + + fileName); //Judge whether the file parent directory exists if (!().exists()) { ().mkdirs(); } try { //Save the file (dest); } catch (Exception e) { ("Save file exception. {}", ()); } } /** * The suffix name of the output file * @param fileName * @return */ public static String getSuffix(String fileName) { // ((".")) // is CThe string operation in # is used to intercept the last point (.) and all the characters after it from the file name string. This operation can be used to obtain the file extension. return ((".")); } /** * New name of the output file (name + suffix) * @param fileName * @return */ public static String generateRandomFileName(String fileName) { return () + getSuffix(fileName); } /** * @param name * @Description Set response header information * @Throws * @Return * @Date 2023-08-02 13:39:15 * @Author lgm */ public static String fileContentType(String name) { String result = ""; String fileType = (); if ((".png")) { result = "image/png"; } else if ((".gif")) { result = "image/gif"; } else if ((".jpg") || (".jpeg")) { result = "image/jpeg"; } else if ((".svg")) { result = "image/svg+xml"; } else if ((".doc")) { result = "application/msword"; } else if ((".xls")) { result = "application/x-excel"; } else if ((".zip")) { result = "application/zip"; } else if ((".pdf")) { result = "application/pdf"; } else if ((".mpeg")) { //MP3 result = "audio/mpeg"; } else if ((".mp4")) { result = "video/mp4"; } else if ((".plain")) { result = "text/plain"; } else if ((".html")) { result = "text/html"; } else if ((".json")) { result = "application/json"; } else{ result = "application/octet-stream"; } return result; } }
5. Downloaded code display
- Business logic code:
/** * Download the file * 1. The file name needs to be passed * 2. First get the file storage path + name * 3. Set the response header to tell the browser that the folder needs to be downloaded * 4. Set the response body, read the file, and write it to the response body * 5. () Output byte stream, the client will download the byte stream and generate a file to save locally * @param filename * @param response * @return * @throws IOException */ @RequestMapping("/fileload") public String fileload(@RequestParam("filename")String filename, HttpServletResponse response) throws IOException { // The file storage location String filePath = "C:\\Users\\liguoming\\Desktop\\" + filename; File file = new File(filePath); // Set the response header to tell the browser to download the file // () is the response type. What file is read by the browser? According to the file type, tell the browser what next to do. // application/octet-stream tells the browser that it needs to download binary stream data (such as common file downloads) ("application/octet-stream"); /** * ("Content-Disposition", "attachment; filename=" +new String( ("gb2312"), "ISO8859-1" )); * When ensuring that the attachment file names are all simplified Chinese, this method is indeed the most effective, and there is no need to let customers upgrade IE one by one. * If * compatriots use it, just change gb2312 to big5. However, today's systems usually have international support, and UTF-8 is widely used. * If the file name contains simplified Chinese, traditional Chinese, and Japanese. Then garbled codes are created. In addition, downloading on Firefox (v1.0-en) is also garbled. */ ("Content-Disposition", "attachment; filename=" +new String( ("gb2312"), "ISO8859-1" )); //() outputs byte stream, the client will download the byte stream and generates a file to save locally ServletOutputStream outputStream = (); ((file)); (); return "success"; }
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.