使用base64上傳檔案,後臺轉為MultipartFile
阿新 • • 發佈:2018-11-10
通常情況下,上傳檔案時,使用的都是file型別。我們再java後臺應用只需要使用MultipartFile接收就可以了。有的時候,或許我們也會遇到使用base64進行檔案上傳。今天,我們一起學習下後臺 應該如何處理這樣的情況。
由於MultipartFile的實現類都不太適用於base64的上傳檔案。所以,我們需要自定義一個實現類:
package space.test.upload.config; import org.springframework.web.multipart.MultipartFile; import java.io.*; /** * 自定義的MultipartFile的實現類,主要用於base64上傳檔案,以下方法都可以根據實際專案自行實現 * * @author zhuzhe * @date 2018/10/17 17:19 * @email
[email protected] */ public class BASE64DecodedMultipartFile implements MultipartFile { private final byte[] imgContent; private final String header; public BASE64DecodedMultipartFile(byte[] imgContent, String header) { this.imgContent = imgContent; this.header = header.split(";")[0]; } @Override public String getName() { return System.currentTimeMillis() + Math.random() + "." + header.split("/")[1]; } @Override public String getOriginalFilename() { return System.currentTimeMillis() + (int) Math.random() * 10000 + "." + header.split("/")[1]; } @Override public String getContentType() { return header.split(":")[1]; } @Override public boolean isEmpty() { return imgContent == null || imgContent.length == 0; } @Override public long getSize() { return imgContent.length; } @Override public byte[] getBytes() throws IOException { return imgContent; } @Override public InputStream getInputStream() throws IOException { return new ByteArrayInputStream(imgContent); } @Override public void transferTo(File dest) throws IOException, IllegalStateException { new FileOutputStream(dest).write(imgContent); } }
同時,需要寫一個base64轉MultipartFile,如下:
package space.test.upload.config; import lombok.extern.slf4j.Slf4j; import org.springframework.web.multipart.MultipartFile; import sun.misc.BASE64Decoder; import java.io.IOException; /** * @author zhuzhe * @date 2018/10/17 17:21 * @email [email protected] */ @Slf4j public class Base64Util { public static MultipartFile base64ToMultipart(String base64) { try { String[] baseStr = base64.split(","); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = new byte[0]; b = decoder.decodeBuffer(baseStr[1]); for(int i = 0; i < b.length; ++i) { if (b[i] < 0) { b[i] += 256; } } return new BASE64DecodedMultipartFile(b, baseStr[0]); } catch (IOException e) { log.error(e.getMessage()); return null; } } }
接下來,就是上傳處理了,廢話不多說,程式碼如下:
/**
* 上傳圖片
*
* @author zhuzhe
* @date 2018/10/17 13:45
* @email [email protected]
*/
@Slf4j
@RestController
public class CommentImageUploadController {
@Value("${fileupload.path}")
private String fileuploadPath;
@RequestMapping(value = "/comment", method = RequestMethod.POST)
public ApiResponse uploadImage(String image, HttpServletResponse response) {
try {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "*");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
MultipartFile multipartFile = Base64Util.base64ToMultipart(image);
String originalFilename = multipartFile.getOriginalFilename();
// 副檔名
String ext = originalFilename.substring(originalFilename.lastIndexOf(".")).trim();
List<String> extList = Arrays.asList(".jpg", ".png", ".jpeg", ".gif");
if (!extList.contains(ext)) {
return ApiResponse.error("圖片格式非法!");
}
String randomFilename = System.currentTimeMillis() + NumberUtil.getRandomString(6) + ext;
//將檔案寫入伺服器
String fileLocalPath = fileuploadPath + "commentImage/" + randomFilename;
File localFile = new File(fileLocalPath);
multipartFile.transferTo(localFile);
//寫入伺服器成功後組裝返回的資料格式
Map<String, Object> fileMap = new HashMap<>();
//檔案存放路徑
fileMap.put("filePath", "commentImage/" + randomFilename);
return ApiResponse.success(fileMap);
} catch (Exception e) {
log.error("公眾號評價商戶上傳圖片失敗:", e);
}
return ApiResponse.error();
}
}
部分程式碼未做展示,但都是與該功能無關!
轉載請務必保留此出處(原作者):https://blog.csdn.net/zhuzhezhuzhe1
版權宣告:本文為原創文章,允許轉載,轉載時請務必以超連結形式標明文章 原始出處 、作者資訊和本宣告。