MultipartFile實現檔案上傳與下載
阿新 • • 發佈:2021-07-26
MultipartFile介紹
在Java中實現檔案上傳、下載操作一直是一種令人煩躁的工作。但是隨著Spring框架的發展,使用Spring框架中的MultipartFile來處理檔案就是一件比較簡單的事情。
MultipartFile類是org.springframework.web.multipart包下面的一個類,如果想使用MultipartFile類來進行檔案操作,那麼一定要引入Spring框架。MultipartFile主要是用表單的形式進行檔案上傳,在接收到檔案時,可以獲取檔案的相關屬性,比如檔名、檔案大小、檔案型別等等。
Controller類
import lombok.extern.slf4j.Slf4j; import org.springframework.core.io.FileSystemResource; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.Objects; /** * 測試檔案下載、上傳、解析 * @auther Yoko */ @RestController @Slf4j @RequestMapping("/file") public class FileTestController { /** * @description 檔案上傳,入參可以根據具體業務進行新增 */ @RequestMapping(value = "/upLoadFile", method = RequestMethod.POST) public void upLoadFile(@RequestBody MultipartFile file) { log.info("測試MultipartFile實現檔案上傳"); // 獲取檔案的完整名稱,檔名+字尾名 System.out.println(file.getOriginalFilename()); // 檔案傳參的引數名稱 System.out.println(file.getName()); // 檔案大小,單位:位元組 System.out.println(file.getSize()); // 獲取檔案型別,並非檔案字尾名 System.out.println(file.getContentType()); try { // MultipartFile 轉 File File resultFile = FileUtil.MultipartFileToFile(file); System.out.println(resultFile.getName()); // File 轉 MultipartFile MultipartFile resultMultipartFile = FileUtil.FileToMultipartFile(resultFile); System.out.println(resultMultipartFile.getSize()); } catch (IOException e) { log.info("檔案轉換異常"); } } /** * @description 檔案下載,入參可以根據具體業務進行新增,比如下載具體編碼的檔案 */ public void downLoadFile() throws IOException { log.info("測試檔案下載至瀏覽器預設地址"); File file = new File("測試檔案.xlsx"); FileSystemResource fileSource = new FileSystemResource(file); FileUtil.downLoadFile(fileSource.getInputStream(), URLEncoder.encode(Objects.requireNonNull(fileSource.getFilename()), "UTF-8")); } }
FileUtil類
學習是一個循序漸進的過程,而學習的時間從來都不晚,只要你開始學習。import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.springframework.core.io.InputStreamResource; import org.springframework.http.HttpHeaders; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.commons.CommonsMultipartFile; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; import java.io.*; import java.util.Objects; /** * @auther Yoko */ public class FileUtil { /** * MultipartFile型別轉File型別,檔名同被轉換檔名稱一致,如有需要可以拓展方法。 */ public static File MultipartFileToFile(MultipartFile multipartFile) throws IOException { if (multipartFile.isEmpty()) { return null; } // 獲取InoutString InputStream inputStream = multipartFile.getInputStream(); // 建立檔案 File toFile = new File(Objects.requireNonNull(multipartFile.getOriginalFilename())); // 寫入檔案 OutputStream outputStream = new FileOutputStream(toFile); byte[] buffer = new byte[8192]; int bytesRead = 0; while ((bytesRead = inputStream.read(buffer, 0, buffer.length)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.close(); inputStream.close(); return toFile; } /** * File型別轉MultipartFile型別,檔名同被轉換檔名稱一致,如有需要可以拓展方法。 */ public static MultipartFile FileToMultipartFile(File file) throws IOException { FileItemFactory factory = new DiskFileItemFactory(16, null); FileItem item = factory.createItem("textField", "text/plain", true, file.getName()); int bytesRead = 0; byte[] buffer = new byte[8192]; FileInputStream fis = new FileInputStream(file); OutputStream os = item.getOutputStream(); while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); fis.close(); return new CommonsMultipartFile(item); } /** * 將File檔案轉化為Base64位元組碼 */ public static String encodeBase64File(File file) throws IOException { FileInputStream inputFile = new FileInputStream(file); byte[] buffer = new byte[(int) file.length()]; int read = inputFile.read(buffer); inputFile.close(); return new BASE64Encoder().encode(buffer); } /** * 將base64字元儲存文字檔案 */ public static void decoderBase64File(String base64Code, String targetPath) throws IOException { byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code); FileOutputStream out = new FileOutputStream(targetPath); out.write(buffer); out.close(); } /** * 下載檔案至瀏覽器預設位置 */ public static ResponseEntity<InputStreamResource> downLoadFile(InputStream in, String fileName) throws IOException { byte[] testBytes = new byte[in.available()]; HttpHeaders headers = new HttpHeaders(); headers.add("Cache-Control", "no-cache, no-store, must-revalidate"); headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", fileName)); headers.add("Pragma", "no-cache"); headers.add("Expires", "0"); return ResponseEntity .ok() .headers(headers) .contentLength(testBytes.length) .contentType(MediaType.parseMediaType("application/octet-stream")) .body(new InputStreamResource(in)); } }