java 上傳圖片到本地指定路徑(並按年月日文件夾分類保存)實例


 工具類方法
PhotoUtils里的方法
//上傳圖片
public static String uploadFile(HttpServletRequest request, MultipartFile uploadFile) throws IOException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSS");
String res = sdf.format(new Date());
//設置的保存路徑
String rootPath ="E://upload/";
//原始名稱
String originalFilename = uploadFile.getOriginalFilename();
//生成文件名
String newFileName = res + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//創建年月日文件夾
Calendar date = Calendar.getInstance();
File dateDirs = new File(date.get(Calendar.YEAR)
+ File.separator + (date.get(Calendar.MONTH) + 1) + File.separator + (date.get(Calendar.DATE)));
//新文件
File newFile = new File(rootPath + File.separator + dateDirs + File.separator + newFileName);
//判斷目標文件所在的目錄是否存在
if (!newFile.getParentFile().exists()) {
//如果目標文件所在的目錄不存在,則創建父目錄
newFile.getParentFile().mkdirs();
}
// System.out.println(newFile);
//將內存中的數據寫入磁盤
uploadFile.transferTo(newFile);
//完整的url
String fileUrl = date.get(Calendar.YEAR) + "/" + (date.get(Calendar.MONTH) + 1) + "/" + (date.get(Calendar.DATE)) + "/" + newFileName;
return fileUrl;
}
/**
* 判斷上傳文件大小方法
*
* @param len
* 文件長度
* @param size
* 限制大小
* @return
*/
public static boolean checkFileSize(Long len, int size) {
double fileSize = 0;
fileSize = (double) len / 1048576;
if (fileSize > size) {
return false;
}
return true;
}
 
        
Controller中的方法

//上傳圖片
@RequestMapping(value = "/imageUpload",method = RequestMethod.POST)
public ResponseOne imageUpload( HttpServletRequest request, MultipartFile multipartFile ) throws IOException {
ResponseOne sendVo = new ResponseOne();
String fileName ="";
//上傳圖片限制大小
Long len = multipartFile.getSize();
boolean isBig= PhotoUtils.checkFileSize(len,4);
if(!isBig){
sendVo.setData(null);
sendVo.setCode(1);
sendVo.setMsg("文件超出4M,請壓縮后重試");
sendVo.setCount(0);
return sendVo;
}

try {
 //上傳實際方法
    if(multipartFile.getSize()!=0) {
fileName = PhotoUtils.uploadFile(request,multipartFile);
}}
//上傳失敗提示
catch (IOException e) {
sendVo.setData(null);
sendVo.setCode(1);
sendVo.setMsg("上傳失敗");
sendVo.setCount(0);
return sendVo;
}
//上傳成功
sendVo.setData(fileName);
sendVo.setMsg("上傳成功");
sendVo.setCount(1);
sendVo.setCode(0);
return sendVo;
}

springBoot 的application.yml配置文件設置上傳圖片限制,不限制的話最大上傳1M會提示報錯

spring:
#文件大小 MB必須大寫
# maxFileSize 是單個文件大小
# maxRequestSize是設置總上傳的數據大小
servlet:
multipart:
enabled: true
max-file-size: 20MB
max-request-size: 20MB




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM