ajax 文件跨域上传

时间:2022-02-17 17:46:59

网上的东西需要消化,并不是一味的copy那只是浪费自己的时间。

 

HTML:

  <form id= "uploadForm">
      <p >指定文件名: <input type="text" name="filename" value= ""/></p >
      <p >上传文件: <input type="file" name="file" id="file"/></ p>
      <input type="button" value="上传" onclick="doUpload()" />
</form>

 

JS:

    <script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript">

function doUpload() {
    //提交form所有的name     写法一:通过form表单获取
 //  var formData = new FormData($("#uploadForm" )[0]);
     ajax 文件跨域上传
    //提交指定的参数        通过本身id获取
    var formData = new FormData();
     formData.append("file",$( "#file" )[0].files[0]);
    ajax 文件跨域上传
     formData.append("filename","aa");
     
     
     $.ajax({
          url: 'http://39.106.14.33:8080/YOBAO.Protal/upload' ,
          type: 'POST',
          data: formData,
          async: false,
          cache: false,
          contentType: false,
          processData: false,
          dataType:"text",
          success: function (data) {
              console.info("success"+data);
              alert(data);
          },
          error: function (data) {
              console.info("error"+data);
              alert(data);
          }
     });
}
</script>

 

 

JAVA服务端:

    @RequestMapping(value = "upload", method = RequestMethod.POST)  
       public @ResponseBody Object  
        upload(/*@RequestParam MultipartFile file,*/  
               @RequestParam(value = "file", required = false) MultipartFile file,  
               String filename,HttpServletRequest request, HttpServletResponse response) {  
        response.setHeader("Access-Control-Allow-Origin", "*");
        System.out.println(file.getOriginalFilename());
        System.out.println(filename);
          return "xxx";  
       }