Write about the functions that are often required for back-end spring projects to upload and download pictures, and the front-end code is also attached here. It may be a simple version. The upload of the pictures here is located in the root directory of the current project.
This includes uploading files, downloading files (downloading file streams, obtaining base64), and there is also a tool method for file streaming base64 in the service.
Below is the backend code
Controller
package ; import ; import ; import ; import ; import ; import .*; import ; import .*; @RestController @RequestMapping("/file") public class TestController { @Autowired TestService testService; /** * File upload * @param file * @return * @throws IOException */ @PostMapping("/upload") public ActionResult uploadTest(@RequestParam("file") MultipartFile file) throws IOException { return (file); } /** * File download * @param name * @return * @throws FileNotFoundException */ @GetMapping("/download/{name}") @CrossOrigin public ResponseEntity<InputStreamResource> downloadTest(@PathVariable("name") String name) throws FileNotFoundException { return (name); } /** * Get the base64 encoding of the file * @param name * @return * @throws IOException */ @GetMapping("/getBase64/{name}") public ActionResult getBase64(@PathVariable("name") String name) throws IOException { return testService.getBase64(name); } }
The Service interface will not be posted
ServiceImpl
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import .*; import ; import .Base64; import ; import ; import ; @Service public class TestServiceImpl implements TestService { /** * File upload logic * @param file * @return * @throws IOException */ @Override public ActionResult upload(MultipartFile file) throws IOException { if(()) { return ("The file cannot be empty"); } // Uploaded file name String originalFilename = (); // File suffix String suffix = ((".")); // Use uuid to store the current file name to prevent the same name from being overwritten String uuid = ().toString(); String fileName = uuid + suffix; // The path to save the file (I exist under the current project here, so get the absolute path of the current project, and then splice the name of the folder stored in the picture on it) String savePath = ("resource").getPath(); // Determine whether the resource directory exists, create it if it does not exist. File dir = new File(savePath); if(dir != null && !()) { (); } savePath = savePath + + fileName; // File upload (new File(savePath)); // Return the file storage name uuid and original file name to the front end Map<String, Object> map = new HashMap<>(); ("id", uuid); ("name", originalFilename); // Return the interface (return file stream) path to the front-end, and the front-end directly splices the server address as the link to echo the picture ("url", "/file/download/" + fileName); return ("Uploaded successfully", map); } /** * File download logic (file stream) * @param name * @return * @throws FileNotFoundException */ @Override public ResponseEntity<InputStreamResource> download(String name) throws FileNotFoundException { String path = ("resource").getPath() + + name; File file = new File(path); if(!()) { return new ResponseEntity<>(HttpStatus.NOT_FOUND); } // Create input stream InputStream inputStream = new FileInputStream(file); // Set HTTP header information HttpHeaders headers = new HttpHeaders(); (() + "---->>>File name"); (HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + ()); // Return to file stream ResponseEntity<InputStreamResource> body = () .headers(headers) .contentType(MediaType.APPLICATION_OCTET_STREAM) .body(new InputStreamResource(inputStream)); return body; } /** * Get the base64 encoding of the file * @param name * @return * @throws IOException */ @Override public ActionResult getBase64(String name) throws IOException { String path = ("resource").getPath() + + name; File file = new File(path); if(!()) { return ("The file does not exist"); } byte[] fileContent = (()); String base64 = ().encodeToString(fileContent); base64 = "data:image/png;base64," + base64; return ((Object) base64); } /** * Transfer files to base64 encoding (tool method, the interface in service does not have this method) * @param response * @return * @throws IOException */ public String streamToBase64(ResponseEntity<InputStreamResource> response) throws IOException { // Get the InputStreamResource object InputStreamResource resource = (); if (resource == null) { throw new IllegalArgumentException("Response body is null"); } try (InputStream inputStream = (); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) { byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = (buffer)) != -1) { (buffer, 0, bytesRead); } // Convert InputStream to byte array byte[] fileBytes = (); // Encoding using Base64 encoder String base64Encoded = ().encodeToString(fileBytes); base64Encoded = "data:image/png;base64," + base64Encoded; return base64Encoded; } } }
Comments are also written in the code, and you should understand it at a glance.
Let me briefly talk about the idea. When storing pictures, I store uuid as the name of the picture. In this way, even if the front end has two files, the names are the same, the original picture will not be overwritten after uploading.
Then after the image is uploaded, I return the path to the front-end. The front-end can use the server address (of course, there will be cross-domain problems in the development environment, and usually use the prefix directly). The returned path can be used to echo the image.
The returned url is actually an interface written by the backend. It returns a file stream. The frontend directly places the path of the backend of the complete request on the src of the img tag, which is actually equivalent to sending a request. Therefore, please note that this method of echoing requires the backend to place the change interface in a whitelist (that is, the interface does not require token verification). Otherwise, the frontend cannot directly place it on the src of the img like a normal path. It must call the interface like an ordinary interface, and then convert it to the path through (new blob(res)) and then copy it to the src.
Then I encapsulated the package class that ActionResult returned to the front end, and I will post it here:
ActionResult
package ; import ; @Data public class ActionResult<T> { private Integer code; private String msg; private T data; public static ActionResult success() { ActionResult jsonData = new ActionResult(); (200); ("success"); return jsonData; } public static ActionResult success(String msg) { ActionResult jsonData = new ActionResult(); (200); (msg); return jsonData; } public static ActionResult success(Object object) { ActionResult jsonData = new ActionResult(); (object); (200); ("success"); return jsonData; } public static ActionResult success(String msg, Object object) { ActionResult jsonData = new ActionResult(); (object); (200); (msg); return jsonData; } public static ActionResult fail(Integer code, String message) { ActionResult jsonData = new ActionResult(); (code); (message); return jsonData; } public static ActionResult fail(String msg, String data) { ActionResult jsonData = new ActionResult(); (msg); (data); return jsonData; } public static ActionResult fail(String msg) { ActionResult jsonData = new ActionResult(); (msg); (400); return jsonData; } }
Next, post the front-end code:
<template> <div class="wft-test"> <el-upload class="avatar-uploader" :action="baseURL + '/file/upload'" :show-file-list="false" :on-success="handleAvatarSuccess" > <img v-if="imageUrl" :src="baseURL + imageUrl" class="avatar" /> <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon> </el-upload> <!-- Test download pictures Get file stream --> <el-button @click="testDownload('')">Test download pictures流</el-button> <!-- Test download pictures Getbase64 --> <el-button @click="testDownloadBase64('')">Test download picturesbase64</el-button> <img style="width: 200px;height: 200px;" v-if="imgBase64" :src="imgBase64" alt=""> </div> </template> <script setup lang='ts'> import { ref } from 'vue'; import request from '@/utils/request'; const imageUrl = ref(""); const imgBase64 = ref(""); // Callback successfully uploadedfunction handleAvatarSuccess(res: any) { if( == 200) { = // Normally successful echo } } /** * Test download image (get file stream) * @param fileName filename */ function testDownload(fileName: string) { request({ url: `/file/download/${fileName}`, method: 'get', responseType: 'blob' }).then((res: any) => { const link = ('a') = (new Blob([res])) = '' (link) () (link) }) } /** * Test download image (get file base64 encoding) * @param fileName */ function testDownloadBase64(fileName: string) { request({ url: `/file/getBase64/${fileName}`, method: 'get' }).then((res: any) => { if( == 200) { = } }) } </script> <style scoped> .wft-test { width: 100%; height: 100%; } .avatar-uploader .avatar { width: 178px; height: 178px; display: block; } </style> <style> .avatar-uploader .el-upload { border: 1px dashed var(--el-border-color); border-radius: 6px; cursor: pointer; position: relative; overflow: hidden; transition: var(--el-transition-duration-fast); } .avatar-uploader .el-upload:hover { border-color: var(--el-color-primary); } .-uploader-icon { font-size: 28px; color: #8c939d; width: 178px; height: 178px; text-align: center; } </style>
The above is the detailed content of springboot's image upload and download function. For more information about springboot's image upload and download, please follow my other related articles!