潮汐王子怎么做,咸蒜头卖仔,福永信用卡套现
效果如下:
1.启动类中加入
springboot重写addresourcehandlers映射文件路径
@override public void addresourcehandlers(resourcehandlerregistry registry) { registry.addresourcehandler("/imctemp-rainy/**").addresourcelocations("file:d:/e/"); }
设置静态资源路径
2. 表单 前端 页面
<input type="file" name="file" id="file"> <p id="url"><img src="" width=200></p> <input type="button" id="button" value="上传" > $(function () { $("#button").click(function () { var form = new formdata(); form.append("file", document.getelementbyid("file").files[0]); $.ajax({ url: "/stu/upload", //后台url data: form, cache: false, async: false, type: "post", //类型,post或者get datatype: 'json', //数据返回类型,可以是xml、json等 processdata: false, contenttype: false, success: function (data) { //成功,回调函数 if (data) { var pic="/imctemp-rainy/"+data.filename; $("#url img").attr("src",pic); // alert(json.stringify(data)); } else { alert("失败"); } }, error: function (er) { //失败,回调函数 alert(json.stringify(data)); } }); }) })
控制器
public static void uploadfile(byte[] file, string filepath, string filename) throws exception { file targetfile = new file(filepath); if (!targetfile.exists()) { targetfile.mkdirs(); } fileoutputstream out = new fileoutputstream(filepath +"/"+ filename); out.write(file); out.flush(); out.close(); } //处理文件上传 @responsebody //返回json数据 @requestmapping(value = "upload", method = requestmethod.post) public jsonobject uploadimg(@requestparam("file") multipartfile file,httpservletrequest request) { string contenttype = file.getcontenttype(); system.out.print(contenttype); string filename = system.currenttimemillis()+file.getoriginalfilename(); string filepath = "d:/e"; jsonobject jo = new jsonobject();//实例化json数据 if (file.isempty()) { jo.put("success", 0); jo.put("filename", ""); } try { uploadfile(file.getbytes(), filepath, filename); jo.put("success", 1); jo.put("filename", filename); // jo.put("xfilename", filepath+"/"+filename); } catch (exception e) { // todo: handle exception } //返回json return jo; }
总结
以上所述是小编给大家介绍的基于spring boot利用 ajax实现上传图片功能,希望对大家有所帮助
如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复
bootstrap select2 动态从后台Ajax动态获取数据的代码
使用ajax跨域调用springboot框架的api传输文件
不使用XMLHttpRequest对象实现Ajax效果的方法小结
网友评论