网站建设资讯

NEWS

网站建设资讯

怎么在SpringBoot中利用ajax上传图片

本篇文章给大家分享的是有关怎么在Spring Boot中利用ajax上传图片,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。

成都创新互联坚持“要么做到,要么别承诺”的工作理念,服务领域包括:网站设计、网站制作、企业官网、英文网站、手机端网站、网站推广等服务,满足客户于互联网时代的汨罗网站设计、移动媒体设计的需求,帮助企业找到有效的互联网解决方案。努力成为您成熟可靠的网络建设合作伙伴!

1.启动类中加入

怎么在Spring Boot中利用ajax上传图片

SpringBoot重写addResourceHandlers映射文件路径

@Override
 public void addResourceHandlers(ResourceHandlerRegistry registry) {
   registry.addResourceHandler("/imctemp-rainy/**").addResourceLocations("file:D:/E/");
 }

设置静态资源路径

2.   表单 前端 页面


$(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上传图片,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注创新互联行业资讯频道。


网页名称:怎么在SpringBoot中利用ajax上传图片
URL链接:http://cdweb.net/article/gssejj.html