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));
}
}