Springboot 圖片上傳、多圖上傳、圖片壓縮(後臺代碼)
話不多說,直接上代碼!
簡單的前端HTML測試代碼
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="LXL/Content/bootstrap/js/jquery-2.0.3.min.js"></script>
<script type="text/javascript">
$(function() {
$('input[id="uploadcyefuji"]').change(function(e){
var formData = new FormData();
formData.append('file', $('#uploadcyefuji')[0].files[0]);
formData.append('pathName', 'test');
$.ajax({
// url 記得寫成自己的接口路徑
url: 'http://192.168.0.100:8443/uploadimgAPP',
type: 'POST',
cache: false,
data: formData,
processData: false,
contentType: false
}).done(function(res) {
alert("上傳成功")
}).fail(function(res) {
alert("上傳失敗");
});
});
});
</script>
</head>
<body>
<input type="hidden" id="insertcyefuji" name="fuji" />
<input type="file" id="uploadcyefuji" name="file" multiple/>
</body>
</html>
後臺Controller
@RequestMapping(value = "/uploadimgAPP", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> upload(@RequestParam("file") MultipartFile[] file,@RequestParam String pathName,
HttpServletRequest request) {
Map<String,Object> map=new HashMap<String, Object>();
if(file!=null&&file.length>0){
String fileName=null;
try {
for (int i = 0; i < file.length; i++) {
if (!file[i].isEmpty()) {
map.put("fileName", uploadImage(FilePath+pathName,pathName, file[i], true));
System.out.println(fileName);
Map<String,String> mapqMap =new HashMap<String, String>();
mapqMap= (Map<String, String>) map.get("fileName");
fileName = mapqMap.get("YT");
System.out.println(fileName);
}
}
//上傳成功
if(fileName!=null){
logger.debug("上傳成功!");
map.put("status", fileName);
}else {
map.put("status", "上傳失敗!文件格式錯誤!");
//throw new RuntimeException("上傳失敗!文件格式錯誤!");
}
} catch (Exception e) {
e.printStackTrace();
map.put("status", "上傳異常!");
}
}else {
map.put("status", "沒有檢測到有效文件!");
}
return map;
}
/**
* 上傳圖片
* 原名稱
* @param request 請求
* @param path_deposit 存放位置(路徑)
* @param file 文件
* @param isRandomName 是否隨機名稱
* @return 完整文件路徑
*/
public Map<String, String> uploadImage(String path,String pathName,MultipartFile file,boolean isRandomName) {
//上傳
try {
String[] typeImg={"gif","png","jpg","jpeg"};
if(file!=null){
String origName=file.getOriginalFilename();// 文件原名稱
System.out.println("上傳的文件原名稱:"+origName);
// 判斷文件類型
String type =origName.indexOf(".")!=-1?origName.substring(origName.lastIndexOf(".")+1, origName.length()):null;
if (type!=null) {
boolean booIsType=false;
for (int i = 0; i < typeImg.length; i++) {
if (typeImg[i].equals(type.toLowerCase())) {
booIsType=true;
}
}
//類型正確
if (booIsType) {
//組合名稱
String fileSrc="";
//是否隨機名稱
if(isRandomName){
origName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_"+UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
}
//判斷是否存在目錄
String path1 = "C:/pingtai/"+pathName+"t";
File Fpath=new File(path);
if(!Fpath.exists()){
Fpath.mkdirs();//創建目錄
}
File Fpath1=new File(path1);
if(!Fpath1.exists()){
Fpath1.mkdirs();//創建目錄
}
//上傳
File targetFile=new File(path,origName);
file.transferTo(targetFile);
//完整路徑
fileSrc="pingtai/"+pathName+"/"+origName;
//壓縮圖片
long size = file.getSize();
double scale = 1.0d ;
if(size >= 200*1024){
if(size > 0){
scale = (200*1024f) / size ;
}
}
try {
if(size < 200*1024){
Thumbnails.of(fileSrc).scale(1f).toFile(fileSrc);
}else{
Thumbnails.of("C:/"+fileSrc).scale(1f).outputQuality(0.25f).toFile("C:/"+fileSrc);
}
} catch (Exception e1) {
}
//縮略圖
String fileSrc1="pingtai/"+pathName+"t/"+origName;
try {
Thumbnails.of("C:/"+fileSrc).scale(0.4f).outputQuality(0.4f).toFile("C:/"+fileSrc1);
}catch(Exception e1){
}
System.out.println("圖片上傳成功:"+fileSrc);
Map<String, String> map = new HashMap<String,String>();
map.put("SL", fileSrc1);//
map.put("YT", fileSrc);
return map;
}
}
}
return null;
}catch (Exception e) {
e.printStackTrace();
return null;
}
}