当前位置: 代码网 > it编程>前端脚本>Ajax > 使用ajax跨域调用springboot框架的api传输文件

使用ajax跨域调用springboot框架的api传输文件

2024年05月18日 Ajax 我要评论
在新项目中使用的是springboot编写的api,涉及到ajax跨域请求和传输文件的问题,在这里记录一下 首先是前台页面的代码<!doctype html><html> &l

在新项目中使用的是springboot编写的api,涉及到ajax跨域请求和传输文件的问题,在这里记录一下
首先是前台页面的代码

<!doctype html>
<html>
 <head>
  <meta charset="utf-8">
  <title>test_api</title>
  <script type="text/javascript" src="jquery-1.7.2.js"></script>
  <script type="text/javascript">
   function test(){
    var obj = new object;
    obj.name = $("#name").val();
    obj.age = $("#age").val();
    var file = document.getelementbyid("file").files[0];
    var formdata = new formdata();
    formdata.append("data",json.stringify(obj));
    formdata.append("file",file);
    $.ajax({
     type:"post",
     url:"http://localhost:8187/test/upload",
     contenttype:false,
     processdata:false,
     data:formdata,
     success:function(data){
       alert(data.msg);
     }
    });
   }
  </script>
 </head>
 <body>
  <div class="">
   <table>
    <tr>
     <td>scompany:</td>
     <td><input type="text" id="name" value="tom" /></td>
    </tr>
    <tr>
     <td>scardtype:</td>
     <td><input type="text" id="age" value="23" /></td>
    </tr>
    <tr>
     <td>file:</td>
     <td><input type="file" id="file" /></td>
    </tr>
   </table>
   <input type="button" onclick="test();" value="提交" />
  </div>
 </body>
</html>

程序入口类的代码

package test;

import javax.servlet.multipartconfigelement;

import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.web.servlet.multipartconfigfactory;
import org.springframework.context.annotation.bean;
import org.springframework.web.servlet.config.annotation.corsregistry;
import org.springframework.web.servlet.config.annotation.webmvcconfigurer;
import org.springframework.web.servlet.config.annotation.webmvcconfigureradapter;

/**
 * hello world!
 *
 */

@springbootapplication
public class app 
{

  public static void main( string[] args )
  {
    springapplication.run(app.class, args);
  }
  //设置ajax跨域请求
  @bean
  public webmvcconfigurer corsconfigurer(){
    return new webmvcconfigureradapter(){

      @override
      public void addcorsmappings(corsregistry registry) {
        registry.addmapping("/**").allowedorigins("*");
      }
    };
  }

  @bean
  public multipartconfigelement multipartconfigelement(){
    multipartconfigfactory factory = new multipartconfigfactory();
    //设置上传文件大小限制
    factory.setmaxfilesize("10mb");
    //设置上传总数据大小
    factory.setmaxrequestsize("15mb");
    return factory.createmultipartconfig();
  }
}

api代码

package test.controller;

import java.io.bufferedoutputstream;
import java.io.file;
import java.io.fileoutputstream;
import java.util.hashmap;
import java.util.list;
import java.util.map;
import javax.servlet.http.httpservletrequest;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.requestmethod;
import org.springframework.web.bind.annotation.restcontroller;
import org.springframework.web.multipart.multipartfile;
import org.springframework.web.multipart.multiparthttpservletrequest;
import test.model.uploadinfo;
import com.alibaba.fastjson.json;
import com.alibaba.fastjson.jsonobject;

@restcontroller
@requestmapping("/test")
public class testcontroller {

  /**
   * 上传文件
   * @param req form请求
   * @return json字符串
   */
  @requestmapping(value="/upload", method=requestmethod.post)
  public string uploadfile(httpservletrequest req){ 
    // 返回结果用 json对象
    jsonobject returnobj = new jsonobject();
    //从请求中获取请求的json字符串
    string strdata = req.getparameter("data");
    //将获取到的json字符串转换为imgidx对象
    uploadinfo info = json.parseobject(strdata, uploadinfo.class);
    //获取上传的文件集合
    list<multipartfile> files = ((multiparthttpservletrequest)req).getfiles("file");
    multipartfile file = files.get(0);
    // 返回信息头部
    map<string, string> header = new hashmap<string, string>();
    header.put("code", "0");
    header.put("msg", "success");
    file file1234 = new file(file.getoriginalfilename());
    //插入数据的影响的数据条数
    int result = 0;
    //将文件上传到save
    if(!file.isempty()){
      try{
        byte[] arr = new byte[1024];
        bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(file1234));
        bos.write(arr);
        bos.flush();
        bos.close();
      }catch(exception e){
        header.put("code", "-1");
        header.put("msg", "errormsg:" + e.getmessage());
      }
    }else{
      header.put("code", "-1");
      header.put("msg", "errormsg:上传文件失败,因为文件是空的");
    }
    string returnstr = returnobj.tojsonstring(header);
    return returnstr;
  }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持代码网。

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com