jQuery上傳檔案的方法
阿新 • • 發佈:2021-11-29
<div id="login-form"> <!--<form id="uploadSongsForm" method="POST" action="/upload" enctype="multipart/form-data">--> <form id="uploadSongsForm" enctype="multipart/form-data"> <div id="showMp3Files" class="tittle" > <div class=" form-group"> <input type="file" name="file" id="mp3Files" > </div> <div class=" form-group"> <button type="reset" id="clearmp3" class="btn btn-dark">清除選擇歌曲</button> </div> <div class=" form-group"> <input type="submit" value="上傳" id="uploadBtn" class=" btn btn-primary" > </div> </div> </form>
jq程式碼
$("#uploadSongsForm").submit(function () { $.post("/upload",{file:file},function(info) { if(info.flag){ alert(info.msg) }else{ //新增失敗 alert(info.msg); } }); return false; });
controller程式碼
private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class); @GetMapping("/upload") public String upload() { return "upload"; } @PostMapping("/upload") @ResponseBody public ResultInfo upload(@RequestParam("file") MultipartFile file) { ResultInfo info=new ResultInfo(); info.setFlag(false); if (file.isEmpty()) { info.setMsg("檔案為空"); info.setFlag(false); return info; } String fileName = file.getOriginalFilename(); String filePath = "/mp3/"; System.out.println("檔名:"+fileName); File dest = new File(filePath + fileName); try { file.transferTo(dest); LOGGER.info("succeed"); info.setFlag(true); info.setMsg("上傳成功"); return info; } catch (IOException e) { LOGGER.error(e.toString(), e); } info.setMsg("上傳失敗"); return info; }
就我的猜測是jq段肯定是有錯誤的。
試著修改過來。
jq的ajax方法:
$(window).ready(function () { $("#uploadBtn").click(function () { var formData=new FormData($("#uploadSongsForm")[0]); alert(formData); $.ajax({ url:"/upload", type:"post", data:formData, cache:false, processData: false, contentType: false, success:function (str) { alert(str); }, erro: function (str) { alert(str) } } ) }) })
這個好處就是,F12,請求的路徑都不顯示在瀏覽器裡。