var data = new FormData()
jQuery.each(jQuery('#file')[0].files, function(i, file){
data.append('file-'+i, file)
})
$.ajax({
method : 'post',
url : SERVER,
processData : false,
contentType : false,
//async : false,
data : { id: "2458" , file : data },
success : function(response){
if(response.success==1){
//do something
}
}
});
我需要将图像上传到第三方api,它接受图像文件和id作为参数。但是,每当我尝试使用上面的代码时,只发送图像对象。我也需要发送id。 screenshot shows only image object being sent
快速帮助将不胜感激。
答案 0 :(得分:1)
您应该只在请求中发送FormData
对象。要将id
参数append()
添加到FormData
,就像对文件一样:
var data = new FormData()
$.each(jQuery('#file')[0].files, function(i, file){
data.append('file-' + i, file)
})
data.append('id', '2458');
$.ajax({
method: 'post',
url: SERVER,
processData: false,
contentType: false,
data: data,
success: function(response) {
if (response.success == 1) { // you should change the success flag to a boolean
//do something
}
}
});
答案 1 :(得分:1)
var imageDetails = {};
FR.onload = function(e) {
$('#img'+imageIndex).attr( "src", e.target.result );
$('#imageHolder'+imageIndex).attr('value', e.target.result );
imageDetails.images[expectedFile.replace(/\. [^/.]+$/, "")]=(e.target.result);
}
FR.readAsDataURL( target.files[0] );
jqxhr = $.ajax( {
'url':"https://url",
'data': JSON.stringify(imageDetails),
'type':'post',
'contentType': "application/json"
})
答案 2 :(得分:1)
提交多部分表单以进行文件上传
<form id="myForm" enctype="multipart/form-data">
<input type="file" name="firstFile" id="file_1" data-filename="image.jpg">
<input type="file" name="SecondFile" id="file_2" data-filename="image2.jpg">
<button id="myFormButton">click</button>
</form>
var formData = new FormData();
$("#myFormButton").on("click", function (e) {
e.preventDefault();
var inputs = $("#myForm input");
$.each(inputs, function (obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
formData.append(name, file, filename);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', 'your server URL', true);
xhr.send(formData);
});