2016-09-21 47 views
5

: BenGönder çok parçalı bir dosya ve ek json form verileri dahil/form-data JQuery AJAX Bu yapıyla bir multipar/form-data mesajı için bekler bir HTTP API var

--boundary 
Content-Disposition: form-data; name=""Meta"" 
Content-Type: application/json 

{""Title"":""title"",""Description"":""description"",""Number"":3} 
--boundary 
Content-Disposition: form-data; name=""file""; filename=""fileName"" 
Content-Type: text/plain 
Content-Transfer-Encoding: 7BIT 

some text content 
--boundary 

var data = new FormData(); 
data.append("Meta", "Content-Type: application/json\r\n\r\n" + [JSON.stringify({ Title: "title", Description: "description", Number: 3})] + "\r\n"); 
data.append('File', document.getElementById("file").files[0]); 

$.ajax({ 
    url: myservice, 
    data: data, 
    cache: false, 
    processData: false, 
    contentType: false, 
    type: 'POST', 
    success: function (data, status, req) { 
     alert("OK"+req); 
    }, 
    error: function (req, status, error) { 
     alert("ERROR"+req); 
    } 
}); 

ben olmayan dosya bölümüne içerik türü eklemek için yetenekli değilim Ancak: mesajın yapısını yapmaya çalışıyorum böyle FormData katiyen.

Bu yaklaşımla, Content-Disposition ve Content-Type arasında artık satır sonu ile bir mesaj hazırlıyorum.

-----------------------------10743159127866 
Content-Disposition: form-data; name="Meta" 

Content-Type: application/json 

{"Title":"title","Description":"description","Number":3} 

-----------------------------10743159127866 
Content-Disposition: form-data; name="File"; filename="b839f0cc60ac4fb68f826b20cd02873b.pdf" 
... 
+0

Tırnak işaretlerini kontrol ettiniz mi (")? Kodunuzu kesen tekliflerde sorun olabilir. –

cevap

0
<script type="text/javascript"> 
    $(document).ready(function() { 
    $("#submit").click(function() { 
    var fileInput = document.getElementById('image'); 
    var file = fileInput.files[0]; 
    var formData = new FormData(); 
    formData.append('file', file); 

     $.ajax({ 
     url: "url.php", 
     type: "POST", 
     data: "file="+file, 
     cache: false, 

     success: function(res) { 
      alert(res); 
     }, 
     error: function(err){ 
      alert(err); 
     } 
     }); 
}); 

});