基于SpringBoot利用ajax实现上传图片功能

来源:脚本之家 时间:2020-11-25

这篇文章主要介绍了Spring Boot利用 ajax实现上传图片功能,本文图文实例相结合,给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下

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实现上传图片功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

来源:脚本之家

链接:https://www.jb51.net/article/174084.htm

项目推荐

A5创业网 版权所有

返回顶部