SpringBoot之文件上傳到服務器
最近在做一個文件上傳的功能,也是比較簡單,這裏算是記錄一下吧
後臺
其實我們最好能區分只是單純的上傳圖片還是其他文件,這裏記錄一個可以傳各種格式文件的和一個特定圖片格式的
1.所有格式的文件:
/**
* 文件上傳
*
* @param
* @return
* @throws Exception
*/
@PostMapping(path = "/fileUpload")
@ResponseBody
public Map<String, Object> fileUpload(@RequestParam("uploadfile") MultipartFile file, HttpServletRequest request) throws Exception {
Map<String, Object> data = new HashMap<String, Object>();
//這裏是拿到文件名
String fileName = file.getOriginalFilename();
String sysTime = DateUtil.getCurrentTime24();
//配置文件配置的上傳地址--服務器地址
String targetDir = propertiesDIY.getUpfilePath();
//這裏是工具類
FileUtil.uploadFile(file.getBytes(), targetDir, fileName);
data.put("fileurl", propertiesDIY.getUpfileUrl() + File.separator + sysTime.substring(0, 8) + File.separator + fileName);
logger.info(" file ==>" + fileName + "==>upload to " + targetDir + "success");
return ResponseUtil.toJson(PltResult.RESULT_0000, data);
}
工具類:
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {
File targetFile = new File(filePath);
if (!targetFile.exists()) {
targetFile.mkdirs();
}
//如果文件存在就先刪除了
File ifFile = new File(filePath + File.separator + fileName);
if (ifFile.exists()) {
logger.debug("File is exists!");
ifFile.delete();
}
//然後再寫文件
FileOutputStream out = null;
try {
out = new FileOutputStream(filePath + File.separator + fileName);
out.write(file);
} catch (Exception e) {
logger.error("Error:", e);
} finally {
if (out != null) {
out.close();
}
}
}
Postman測試:
服務器看到的:
2.圖片格式的文件:
這個思路就是前端先把圖片用base64讀取壓縮成字符串,然後再把字符串寫入成圖片
//image就是base64的字符串格式
byte[] imageByte = Base64Helper.decode(image);
File file = new File(filepath + filename);
RandomAccessFile randomAccessFile = null;
try{
randomAccessFile=new RandomAccessFile(file,"rw");
randomAccessFile.seek(0);
try{
randomAccessFile.write(imageByte);
}catch(UnsupportedEncodingException e){
logger.error("Error:",e);
}
}catch(IOException e){
logger.error("Error:",e);
throw e;
}finally{
if(randomAccessFile!=null){
try{
randomAccessFile.close();
}catch(IOException e){
logger.error("Error:",e);
}
}
}