[英]Sending data with a file in a post request
我正在使用 Angular 11 將文件發送到我的節點/express.js 后端如何將數據與文件一起發送?
我有一個稱為源的架構,另一個稱為 files,文件架構包含源架構 ID,以指示哪些文件屬於哪些源。 在我的 angular 應用程序中,我遍歷從源文檔中獲取的數據以顯示它們,顯示的每個源都有一個上傳文件的選項。
我希望能夠在我的發布請求中將源 ID 與文件一起發送,以便將其存儲在我的數據庫中。
這是我使用的代碼:
source.component.ts
@Component({
selector: 'app-source',
templateUrl: './source.component.html',
styleUrls: ['./source.component.scss'],
})
export class SourceComponent implements OnInit {
showModal: boolean = false;
faUpload = faUpload;
@Input() datasource: {
_id: string;
name: string;
description: string;
imagePath: string;
};
@Input() searchPlaceHolder1: string;
@Input() searchPlaceHolder2: string;
isModalActive: boolean = false;
@Output() messageEvent = new EventEmitter<string>();
select: string = 'not selected yet';
searchText: string = '';
fileArr = [];
sheetArr = [];
fileObj = [];
form: FormGroup;
msg: string;
progress: number = 0;
isButtonVisible: boolean = true;
constructor(
public fb: FormBuilder,
private sanitizer: DomSanitizer,
public dragdropService: DragdropService
) {
this.form = this.fb.group({
txt: [null],
});
}
ngOnInit(): void {}
onSelect() {
this.select = 'selected';
}
sendMessage() {
this.messageEvent.emit(this.datasource.name);
}
upload(e) {
const fileListAsArray = Array.from(e);
fileListAsArray.forEach((item, i) => {
const file = e as HTMLInputElement;
const url = URL.createObjectURL(file[i]);
this.sheetArr.push(url);
this.fileArr.push({ item, url: url });
});
this.fileArr.forEach((item) => {
this.fileObj.push(item.item);
});
// Set files form control
this.form.patchValue({
txt: this.fileObj,
});
this.form.get('txt').updateValueAndValidity();
// Upload to server
this.dragdropService
.addFiles(this.form.value.txt)
.subscribe((event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Sent:
console.log('Request has been made!');
break;
case HttpEventType.ResponseHeader:
console.log('Response header has been received!');
break;
case HttpEventType.UploadProgress:
this.progress = Math.round((event.loaded / event.total) * 100);
console.log(`Uploaded! ${this.progress}%`);
break;
case HttpEventType.Response:
console.log('File uploaded successfully!', event.body);
setTimeout(() => {
this.progress = 0;
this.fileArr = [];
this.fileObj = [];
this.msg = 'File uploaded successfully!';
}, 3000);
}
});
}
// Clean Url
sanitize(url: string) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
loading = { 1: false, 2: false, 3: false, 4: false };
doSomething(i: number) {
console.log('Clicked');
this.loading[i] = true;
setTimeout(() => {
this.loading[i] = false;
}, 2000);
}
selectItem() {
this.showModal = true;
}
}
拖放.service.ts
@Injectable({
providedIn: 'root',
})
export class DragdropService {
constructor(private http: HttpClient) {}
addFiles(sheets: File) {
var arr = [];
var formData = new FormData();
arr.push(sheets);
arr[0].forEach((item, i) => {
formData.append('txt', arr[0][i]);
});
return this.http
.post('http://localhost:4000/upload-file', formData, {
reportProgress: true,
observe: 'events',
})
.pipe(catchError(this.errorMgmt));
}
errorMgmt(error: HttpErrorResponse) {
let errorMessage = '';
if (error.error instanceof ErrorEvent) {
// Get client-side error
errorMessage = error.error.message;
} else {
// Get server-side error
errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
}
console.log(errorMessage);
return throwError(errorMessage);
}
}
至於后端代碼:
app.post("/upload-file", uploads.single("txt"), (req, res) => {
//convert csvfile to jsonArray
if (
req.file.mimetype === "application/vnd.ms-excel" ||
req.file.mimetype === "application/csv" ||
req.file.mimetype === "text / csv"
) {
const fileName = req.file.originalname;
csv({
delimiter: ";",
})
.fromFile(req.file.path)
.then((jsonObj) => {
//insertmany is used to save bulk data in database.
//saving the data in collection(table)
//finding the document using fileName and setting csvData as the jsonObj
sheetModel.findOneAndUpdate(
{ fileName: fileName },
{ $set: { csvData: jsonObj } },
{ upsert: true }, // if name does not exist insert
(err, csvData) => {
if (err) {
res.status(400).json({
message: "Something went wrong!",
});
} else {
res.status(200).json({
message: "File Uploaded Successfully!",
result: csvData,
});
}
}
);
});
}
只需以與添加文件相同的方式將附加字段添加到formData
:
formData.append('sourceId', sourceId);
您似乎在服務器上使用 Multer 中間件。 根據文檔,“ req.body
將保存文本字段,如果有的話”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.