admin管理员组

文章数量:1404767

I'm trying to upload a file and send that via api as a file.But not getting working. Here is my used for upload and send my file to api. But it most probably terns to the error message.

$(document).on('change', '#txtUploadFile', function(e){

    var files = e.target.files;
    if (files.length > 0) {
       if (this.value.lastIndexOf('.xlsx') === -1){
          alert('Only ods files are allowed!');
          this.value = '';
          return;
       }
       if (window.FormData !== undefined) {
           var data = new FormData();
           for (var x = 0; x < files.length; x++){
               data.append("file" + x, files[x]);
           }

           $.ajax({
               type: "POST",
               contentType: "multipart/form-data",
               url: 'http://localhost/clicportaltest/rest/clicadmin/uploadExcel',

               data:{file:file},
               success: function(result) {
                   console.log(result);
               },
               error: function (xhr, status, p3, p4){
                   var err = "Error " + " " + status + " " + p3 + " " + p4;
                   if (xhr.responseText && xhr.responseText[0] == "{")
                       err = JSON.parse(xhr.responseText).Message;
                       console.log(err);
                    }
                });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
          }
     }
});

I'm trying to upload a file and send that via api as a file.But not getting working. Here is my used for upload and send my file to api. But it most probably terns to the error message.

$(document).on('change', '#txtUploadFile', function(e){

    var files = e.target.files;
    if (files.length > 0) {
       if (this.value.lastIndexOf('.xlsx') === -1){
          alert('Only ods files are allowed!');
          this.value = '';
          return;
       }
       if (window.FormData !== undefined) {
           var data = new FormData();
           for (var x = 0; x < files.length; x++){
               data.append("file" + x, files[x]);
           }

           $.ajax({
               type: "POST",
               contentType: "multipart/form-data",
               url: 'http://localhost/clicportaltest/rest/clicadmin/uploadExcel',

               data:{file:file},
               success: function(result) {
                   console.log(result);
               },
               error: function (xhr, status, p3, p4){
                   var err = "Error " + " " + status + " " + p3 + " " + p4;
                   if (xhr.responseText && xhr.responseText[0] == "{")
                       err = JSON.parse(xhr.responseText).Message;
                       console.log(err);
                    }
                });
        } else {
            alert("This browser doesn't support HTML5 file uploads!");
          }
     }
});
Share Improve this question edited May 15, 2017 at 10:21 Midhun asked May 15, 2017 at 9:31 MidhunMidhun 1151 gold badge1 silver badge10 bronze badges 3
  • What is the error message that you get? – Sventies Commented May 15, 2017 at 9:38
  • How do you expect to encode your files as JSON? Or rather, what format is the server expecting the files to be in? – Quentin Commented May 15, 2017 at 9:53
  • 1 You used to say you were sending JSON, not you say you are sending multipart form data (which the rest of your code isn't doing). The code won't pile (it looks like you changed your mind about making a variable name plural half way through). You keep editing the code, but you still haven't told us what format the HTTP endpoint you are posting the data to is expecting the data in. – Quentin Commented May 15, 2017 at 10:24
Add a ment  | 

2 Answers 2

Reset to default 2
$(function(){
$('#submitUpload').on('click', function(){
    var file = document.getElementById("upload").files[0];
    var form = new FormData();
    form.append("file", file);

    var settings = {
      "async": true,
      "crossDomain": true,
      "url": "http://localhost/clicportaltest/rest/clicadmin/uploadExcel",
      "method": "POST",
      "processData": false,
      "contentType": false,
      "mimeType": "multipart/form-data",
      "data": form
    };

    $.ajax(settings).done(function (response) {
      console.log(response);
    });
  });
});

You can't JSON.stringify data because FormData doesn't have a toJSON() method, so it is treated as a plain object which results in "{}".

You can either implement your own FormData.prototype.toJSON method or just convert data to a string or a plain object in your handler. How the stringified representation of data should be formatted depends entirely on how your API expects it to be.

本文标签: ajaxfile upload in javascript and send file through apiStack Overflow