我知道这是一个非常普遍的问题,但我在Angular 2中上传文件失败了。 我试过了
1) http://valor-software.com/ng2-file-upload/
2) http://ng2-uploader.com/home
...但失败了。有人在Angular中上传过文件吗?你用了什么方法?怎么做呢?如果提供了任何示例代码或演示链接,将非常感谢。
我知道这是一个非常普遍的问题,但我在Angular 2中上传文件失败了。 我试过了
1) http://valor-software.com/ng2-file-upload/
2) http://ng2-uploader.com/home
...但失败了。有人在Angular中上传过文件吗?你用了什么方法?怎么做呢?如果提供了任何示例代码或演示链接,将非常感谢。
当前回答
这是一个有用的教程,如何使用ng2-file-upload和不使用ng2-file-upload上传文件。
对我来说很有帮助。
目前,教程包含几个错误:
1-客户端应具有与服务器相同的上传url 在app.component.ts中更改行
const URL = 'http://localhost:8000/api/upload';
to
const URL = 'http://localhost:3000';
2-服务器发送响应为'text/html',所以在app.component.ts更改
.post(URL, formData).map((res:Response) => res.json()).subscribe(
//map the success function and alert the response
(success) => {
alert(success._body);
},
(error) => alert(error))
来
.post(URL, formData)
.subscribe((success) => alert('success'), (error) => alert(error));
其他回答
我已经成功地使用了下面的工具。我和primeNg没有利害关系,只是传递我的建议。
http://www.primefaces.org/primeng/#/fileupload
Angular 2对上传文件提供了很好的支持。不需要第三方库。
<input type="file" (change)="fileChange($event)" placeholder="Upload file" accept=".pdf,.doc,.docx">
fileChange(event) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let file: File = fileList[0];
let formData:FormData = new FormData();
formData.append('uploadFile', file, file.name);
let headers = new Headers();
/** In Angular 5, including the header Content-Type can invalidate your request */
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
let options = new RequestOptions({ headers: headers });
this.http.post(`${this.apiEndPoint}`, formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
使用@angular/core": "~2.0.0"和@angular/http: "~2.0.0"
jspdf和Angular 8
我生成了一个pdf,并希望通过POST请求上传pdf,这就是我所做的(为了清晰起见,我删除了一些代码和服务层)
import * as jsPDF from 'jspdf';
import { HttpClient } from '@angular/common/http';
constructor(private http: HttpClient)
upload() {
const pdf = new jsPDF()
const blob = pdf.output('blob')
const formData = new FormData()
formData.append('file', blob)
this.http.post('http://your-hostname/api/upload', formData).subscribe()
}
下面的代码以最简单的形式在Angular 6/7中工作
this.http.post("http://destinationurl.com/endpoint", fileFormData)
.subscribe(response => {
//handle response
}, err => {
//handle error
});
下面是完整的实现
尽量不要设置options参数
这个http post(美元(this。apiEndPoint), formData)
并且确保你没有在你的Http工厂中设置globalHeaders。