gpt4 book ai didi

node.js - 文件上传适用于 postman ,但不适用于 Angular2

转载 作者:太空宇宙 更新时间:2023-11-04 00:10:17 25 4
gpt4 key购买 nike

我对 Angular 2 还很陌生,请考虑一下。

我在使用 Angular 2 将文件上传到 Node 服务器时遇到问题。使用 postman 可以正常工作:

postman 快照:

enter image description here

但是,当我使用 Angular2 应用程序将文件发送到服务器时,它什么也不做:

Angular HTML 组件

<label for="file1">Upload PDF version: </label>
<form class="form-inline">
<div class="form-group">
<input type="file" id="file1" #abc name="fileToUpload" class="form-control" placeholder="Upload PDF">
</div>
<button class="btn btn-primary" type="submit" (click)="onUpload(abc)">Upload</button>
</form>

Angular TS 组件:

import { Component, OnInit } from '@angular/core';
import { UploadService } from './upload.service';
import { NgForm } from '@angular/forms';

@Component({
selector: 'app-upload',
templateUrl: './upload.component.html',
styleUrls: ['./upload.component.css']
})
export class UploadComponent implements OnInit {

// file1 = document.getElementById("file1");
constructor(private uploadService: UploadService) { }

ngOnInit() {
}

onUpload = (file: File) => {
this.uploadService.uploadfile(file)
.subscribe((res) => {
console.log(res);
},

(err) => {
console.log(err);
});
}

}

服务组件:

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '@angular/common/http';


@Injectable()
export class UploadService {

constructor(private http: HttpClient) {
}

uploadfile(file: File): Observable<File> {

console.log(file);
return this.http.post<File>("http://localhost:3000/fileupload", file, { headers: { 'Content-Type': 'application/json' } });
}

}

当然,我一定错过了一些东西。请大家提供一些解决方案。

最佳答案

您必须创建 formData 才能上传文件。下面是示例代码。

      fileDetails: any = {
clientDoc: {}
};
uploadClientDoc(event) {
this.fileDetails.clientMandateForm = event.srcElement.files[0];
this.submitFlag = this.fileDetails.isdaFile ? true : false;
}

submit() {
let formData: FormData = new FormData();
formData.append('clientDoc', this.fileDetails.clientDoc);
var data = this.urService.uploadFiles(formData).subscribe(res => {
//your login
});

}



uploadFiles(data) {
const httpOptions = {
headers: new HttpHeaders({
'Accept': 'application/json',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'multipart/form-data'
})
};

return this.http.post('<url>', data, httpOptions);
}






<div>
<label>Please Select Document</label>
<label class="type-file">+ Upload FIle
<input type="file" accept="application/pdf" id="my_file1" (change)="uploadClientDoc($event)" />
</label>
<label >{{fileDetails.clientDoc.name}}</label>
</div>

<button class="ci-btn float-right-btn" type="button" (click)="submit()" value="Submit">Submit</button>

关于node.js - 文件上传适用于 postman ,但不适用于 Angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50055258/

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