最近在使用一個wangEditor富文本編輯器,這個富文本編輯器有一個上傳檔案的功能,搞了兩天的時間終于終于可以成功的删除上傳圖檔了,
遇到的問題一共有兩個,一個是我使用SpringMVC,一開始上傳檔案背景是無法接收到的,也就是檔案被攔截了
還有一個問題是是背景傳回的資料格式不對,是以雖然說檔案是上傳到我們對應的檔案夾裡面了,但是前台還是一直提示檔案上傳錯誤
現在我是講最終的展示出來,應該可以直接拿去用了:
var editor = new wangEditor('#txtDiv');
editor.customConfig.uploadImgServer = serviceUrl+'/Shopping/filecontroller/uploadfile';
/* editor.customConfig.uploadImgFileName = 'myFileName';*/
editor.customConfig.uploadImgShowBase64 = true;
editor.customConfig.showLinkImg = false;
editor.customConfig.debug=true;
editor.customConfig.uploadImgHooks = {
success: function (xhr, editor, result) {
// 圖檔上傳并傳回結果,圖檔插入成功之後觸發
// xhr 是 XMLHttpRequst 對象,editor 是編輯器對象,result 是伺服器端傳回的結果
console.log(result);
}
}
editor.create();
建立wangEditor編輯器,
對應的背景java檔案的是:
@RequestMapping(value = "/uploadfile")
public String uploadFile(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
log.info("-------------------開始調用上傳檔案uploadfile接口-------------------");
String path = this.getClass().getClassLoader().getResource("/").getPath();
int index = path.indexOf("Shopping");
path = path.substring(0, index + "Shopping".length()) + "/WebContent/resources/upload/";
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8"); // 進行中文問題
sfu.setSizeMax(1024 * 1024); // 限制檔案大小
String fileName = "";
try {
List<FileItem> fileItems = sfu.parseRequest(request);
for (FileItem item : fileItems) {
fileName = UUID.randomUUID().toString() + item.getFieldName()
.substring(item.getFieldName().lastIndexOf('.'), item.getFieldName().length());
item.write(new File(path + "//" + fileName));
}
} catch (Exception e) {
e.printStackTrace();
}
// 擷取圖檔url位址
JSONObject json=new JSONObject();
JSONArray arr=new JSONArray();
String imgUrl = "http://localhost:8080/Shopping/resources/upload/" + fileName;
arr.add(imgUrl);
json.put("errno", 0);
json.put("data", arr);
response.setContentType("text/text;charset=utf-8");
PrintWriter out = response.getWriter();
out.print(json.toString());
out.flush();
out.close();
log.info("-------------------結束調用上傳檔案uploadfile接口-------------------");
return "nihao";
}
這樣前台就可以正常的插入圖檔了