使用AJAX實(shí)現(xiàn)上傳文件
本文實(shí)例為大家分享了使用ajax實(shí)現(xiàn)上傳文件的具體代碼,供大家參考,具體內(nèi)容如下
需求:
在前端頁(yè)面選擇文件上傳到服務(wù)器的指定位置
前端代碼
上傳電子書(shū) 上傳
$("#upload").click(function () { var formdata = new formdata($('#uploadform')[0]); $.ajax({ type: 'post', url: "https://****:8443/fileupload", //上傳文件的請(qǐng)求路徑必須是絕對(duì)路勁 data: formdata, cache: false, processdata: false, contenttype: false, }).success(function (data) { console.log(data); alert("上傳成功"+data); filename=data; }).error(function () { alert("上傳失敗"); }); });
首先創(chuàng)建一個(gè)formdata實(shí)例,也就是空對(duì)象,將頁(yè)面中現(xiàn)有form表單將他初始化。通過(guò)ajax提交給后臺(tái)
后端代碼
@postmapping(value = "/fileupload") @responsebody public string fileupload(@requestparam(value = "file") multipartfile file, model model, httpservletrequest request) { if (file.isempty()) { system.out.println("文件為空空"); } string filename = file.getoriginalfilename(); // 文件名 system.out.println(file.getoriginalfilename()); string suffixname = filename.substring(filename.lastindexof(".")); // 后綴名 string filepath = "c://pdf//"; // 上傳后的路徑 filename = uuid.randomuuid() + suffixname; // 新文件名 file dest = new file(filepath + filename); system.out.println("pdf文件路徑為:"+dest.getpath()); if (!dest.getparentfile().exists()) { dest.getparentfile().mkdirs(); system.out.println("上傳pdf文件+++++++++++"); system.out.println("pdf文件路徑為:"+dest.getpath()); } try { file.transferto(dest); } catch (ioexception e) { e.printstacktrace(); } string filename = "/pdf/" + filename; return filename; }
注意
1.@requestparam(value = “file”) 中的file需要和input中的name屬性一致。
2.提交按鈕類(lèi)型type=“button”如果為“submit”的話,提交完數(shù)據(jù)會(huì)刷新一次頁(yè)面。