springboot中使用js.ajax()方法和multipartfile類實現檔案非同步上傳-springboot(2)
阿新 • • 發佈:2018-12-22
前言
今天忽然發現,之前springmvc中我經常使用的檔案上傳的js包不可用在springboot中不可用了,使用包裡的方法訪問不到後臺上傳檔案介面,只能自己重新實現了。
之前沒有接觸過這塊,世紀專案中也只用到過幾次而已,只好多踩一踩坑
正文
直接先把程式碼列出來吧
後臺controller
/** * 檔案上傳 * @param file 接收前端的formdata * @return 包含上傳資訊的json */ @RequestMapping(value = "/fileup", method = RequestMethod.POST) @ResponseBody public JSONObject singleFileUpload(@RequestParam("file")MultipartFile file){ JSONObject jsonObject = new JSONObject(); if (file.isEmpty()) { jsonObject.put("result", -1); return jsonObject; } String fileName = file.getOriginalFilename(); StringBuilder stringBuilder = new StringBuilder(); File fileDir = new File("src/main/resources/static/"); String path = fileDir.getAbsolutePath(); if(!fileDir.exists()){ fileDir.mkdir(); } try { file.transferTo(new File(path, fileName)); jsonObject.put("result", 1); jsonObject.put("message", "ok"); jsonObject.put("url", stringBuilder.append(path).append(fileName).toString()); } catch (Exception e) { jsonObject.put("result", 0); e.printStackTrace(); } return jsonObject; }
將檔案儲存在src/main/resources/static/
下,並且使用檔案原名。
前端程式碼:
前端要引入jquery,要用到$.ajax()
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Uplaod</title> <script type="text/javascript" src="js/jquery-3.3.1.min.js"></script> </head> <body> <!--<form action="http://localhost:8080/fileup" enctype="multipart/form-data" method="post">--> <!--<input type="file" id="file" name="file">--> <!--<input type="submit" id="butto" value="上傳">--> <!-- </form>--> <p>JSON</p> <input type="file" id="file" name="file"> <input type="button" id="button" value="上傳" > 返回的url為:<p id="url"></p> </body> <script type="text/javascript"> $(function () { $("#button").click(function () { var form = new FormData(); form.append("file", document.getElementById("file").files[0]); $.ajax({ url: "http://localhost:8080/fileup", //後臺url data: form, cache: false, async: false, type: "POST", //型別,POST或者GET dataType: 'json', //資料返回型別,可以是xml、json等 processData: false, contentType: false, success: function (data) { //成功,回撥函式 if (data.result == 1) { $("#url").html(data.url); alert("成功!") } else { alert("失敗"); } }, error: function (er) { //失敗,回撥函式 alert(er); } }); }) }) </script> </html>
註釋掉的是通過form表單提交,會存在頁面重新整理的感覺。
執行試試
提交後,前端顯示上傳成功
在後臺檢視
OK,程式碼可用。