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