layui富文本圖片上傳 + Java後臺代碼
廢話不多說,直接上代碼
前端JS
layedit.set({
uploadImage: {
url: 'http://192.168.5.27:446/fillupf' //接口url
,type: 'post' //默認post
}
});
後臺JAVA
@ResponseBody
@RequestMapping(value = "fillupf", method = RequestMethod.POST)
public String fillupf(@RequestParam("file") MultipartFile[] files) {
try {
//兩個Map用於返回規定格式參數
Map<String,Object> map = new HashMap<String,Object>();
Map<String,Object> map2 = new HashMap<String,Object>();
String[] courseware = new String[files.length];
int index = 0;
//本來就是單圖,這個foreach沒啥用
for (MultipartFile file : files) {
if (!file.isEmpty()) {
String origName=file.getOriginalFilename();// 文件原名稱
System.out.println("上傳的文件原名稱:"+origName);
//類型正確
//組合名稱
String fileSrc="";
//是否隨機名稱
origName=new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"_"+UUID.randomUUID().toString()+origName.substring(origName.lastIndexOf("."));
//判斷是否存在目錄
String path1 = "C:/qvmei/";
File Fpath1=new File(path1);
if(!Fpath1.exists()){
Fpath1.mkdirs();//創建目錄
}
//上傳
File targetFile=new File(path1,origName);
file.transferTo(targetFile);
//完整路徑
fileSrc="http://192.168.5.27:4466/Qmyp/"+origName;
map.put("code",0);//0表示成功,1失敗
map.put("msg","上傳成功");//提示消息
map.put("data",map2);
map2.put("src",fileSrc);//圖片url
map2.put("title",origName);//圖片名稱,這個會顯示在輸入框裏
JSONObject jsonObject = JSONObject.fromObject(map);
String result = jsonObject.toString();
return result;
}
}
map.put("code",1);//0表示成功,1失敗
map.put("msg","上傳失敗");//提示消息
map.put("data",map2);
map2.put("src","");//圖片url
map2.put("title","圖片丟失");//圖片名稱,這個會顯示在輸入框裏
JSONObject jsonObject = JSONObject.fromObject(map);
String result = jsonObject.toString();
return result;
} catch(Exception e) {
}
return null;
}