gpt4 book ai didi

javascript - 以 Angular 将文件附加到 FormData 后无法上传文件

转载 作者:行者123 更新时间:2023-12-02 22:27:08 24 4
gpt4 key购买 nike

我正在尝试将 post 请求中的文件发送到我的后端,它以状态 500 响应,因为请求中没有文件 --> 检查后,我的 formData 似乎是空的并且不包含任何文件.

这是我的功能:

  createProductsByCsv(): void {
const self = this;
const setting: any = {
title: '<h5>Add Products By CSV file</h5>',
html:
'<div class="form-group row">\n' +
' <label class="col-sm-4 col-form-label">File</label>\n' +
' <div class="col-sm-8">\n' + '<input type="file" accept=".csv" name="csv-file" id="csv-file" class="form-control datepicker" placeholder="chose csv file">' +
' </div>\n' +
'</div>',
confirmButtonText: 'add the file',
focusConfirm: false,
showLoaderOnConfirm: true
};

setting.preConfirm = (text) => {
var file = $('#csv-file').prop('files')[0];
// console.log(file);

var formData = new FormData();
formData.append('file', file, file.name);
console.log(formData);

if(((file.name.split(".").length -1) > 1) && (file.name.endswith('.csv')))
return self.sweetAlert.error({title: 'Error', text: "Upload only files that ends with .csv and containe single dot otherwise it will be ignored !"});
else
return self.httpApi.post('/catalog/product/filetest',formData).toPromise()
.then(resp => {
if (resp.status == 200) {
self.sweetAlert.success({title: 'Success', text: JSON.stringify(resp.message )});
} else {
self.sweetAlert.error({title: 'Error', text: JSON.stringify(resp.message )});
}
})
.catch(msg => console.log('ERROR' + msg.message + ' ' + msg.message));
};
swal.queue([setting]); }

我做错了什么吗?

最佳答案

尝试这样:

.html

<input #fileInput type="file" accept=".csv" name="csv-file" id="csv-file" class="form-control datepicker" placeholder="chose csv file">

<button (click)="saveFile(fileInput)">Upload</button>

.ts

 saveFile(fileInput) {
let fi = fileInput;

if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];

let formData: FormData = new FormData();
formData.append("file", fileToUpload);

console.log(formData);
...
// http call
}
}

关于javascript - 以 Angular 将文件附加到 FormData 后无法上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59026523/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com