本文实例为大家分享了使用ajax实现上传文件的具体代码,供大家参考,具体内容如下
需求:
在前端页面选择文件上传到服务器的指定位置
前端代码
<form id="uploadform" method="post" enctype="multipart/form-data"> <label >上传电子书</label> <input type="file" name="file" > <button id="upload" type="button" name="button" >上传</button> </form>
$("#upload").click(function () { var formdata = new formdata($('#uploadform')[0]); $.ajax({ type: 'post', url: "https://****:8443/fileupload", //上传文件的请求路径必须是绝对路劲 data: formdata, cache: false, processdata: false, contenttype: false, }).success(function (data) { console.log(data); alert("上传成功"+data); filename=data; }).error(function () { alert("上传失败"); }); });
首先创建一个formdata实例,也就是空对象,将页面中现有form表单将他初始化。通过ajax提交给后台
后端代码
@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.提交按钮类型type=“button”如果为“submit”的话,提交完数据会刷新一次页面。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持www.887551.com。
黄山市民网:https://www.huangshanshimin.com/