我使用fetch Web API从几个网址中检索文件内容并将其发送到表单。但是,当从表单POST ajax请求发送到后端时,我没有在那里使用实际的文件对象,而是检索Promise对象(无法在后端处理)。
下面的代码在发送到$ .ajax以获取File对象时阻止了infile
和mapfile
变量有什么问题?
let formData = new FormData();
let exampleb2pPromise = fetch( fileHash["infile"].fileURL).then(function(response) {
fileHash["infile"].blob = response.blob();
return fileHash;
}).then(function(fileHash) {
let infile = new File( [ fileHash["infile"].blob ], fileHash["infile"].filename, { type: fileHash["infile"].filetype } );
return infile;
});
let exampleCSVPromise = fetch(fileHash["mapfile"].fileURL).then(function(response) { ...
Promise.all([exampleb2pPromise, exampleCSVPromise]).then(function(values) {
let infile = values[0];
let mapfile = values[1];
if ( infile && mapfile ) ) {
console.log( infile );
formData.append( "infile", infile, "input.tsv" );
if ( mapfile ) {
console.log( mapfile );
formData.append( "mapfile", mapfile, "mapfile.txt" );
}
}
return formData;
}).then( function( formData ) {
let exec = "/submit";
console.log( formData );
$.ajax({
url : exec,
type: "POST",
data : formData,
processData: false,
contentType: false,
success:function(data, textStatus, jqXHR){
if ( data && data.session ) {
...
}
},
error: function(jqXHR, textStatus, errorThrown){
//if fails
// TODO: To be handled
}
});
});
答案 0 :(得分:1)
response.blob()
返回Promise
- 您需要重写代码
let exampleb2pPromise = fetch( fileHash["infile"].fileURL).then(function(response) {
return response.blob();
}).then(function(blob) {
fileHash["infile"].blob = blob;
return fileHash;
}).then(function(fileHash) {
let infile = new File( [ fileHash["infile"].blob ], fileHash["infile"].filename, { type: fileHash["infile"].filetype } );
return infile;
});
虽然,编写它更容易:
let exampleb2pPromise = fetch( fileHash.infile.fileURL)
.then(response => response.blob())
.then(blob => new File(fileHash.infile.blob = blob, fileHash.infile.filename, { type: fileHash.infile.filetype } ));