当前位置: 移动技术网 > IT编程>脚本编程>Ajax > 使用ajax跨域调用springboot框架的api传输文件

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

2020年03月09日  | 移动技术网IT编程  | 我要评论

条形码扫描软件,狼族少年迅雷下载,800导航

在新项目中使用的是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;
  }
}

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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网