我知道这是一个非常普遍的问题,但我在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));
其他回答
尽量不要设置options参数
这个http post(美元(this。apiEndPoint), formData)
并且确保你没有在你的Http工厂中设置globalHeaders。
今天我在我的angular 6应用中集成了ng2文件上传包,它非常简单,请找到下面的高级代码。
导入ng2-file-upload模块
app.module.ts
import { FileUploadModule } from 'ng2-file-upload';
------
------
imports: [ FileUploadModule ],
------
------
组件的文件导入FileUploader
app.component.ts
import { FileUploader, FileLikeObject } from 'ng2-file-upload';
------
------
const URL = 'http://localhost:3000/fileupload/';
------
------
public uploader: FileUploader = new FileUploader({
url: URL,
disableMultipart : false,
autoUpload: true,
method: 'post',
itemAlias: 'attachment'
});
public onFileSelected(event: EventEmitter<File[]>) {
const file: File = event[0];
console.log(file);
}
------
------
组件HTML添加文件标签
app.component.html
<input type="file" #fileInput ng2FileSelect [uploader]="uploader" (onFileSelected)="onFileSelected($event)" />
Working Online stackblitz链接:https://ng2-file-upload-example.stackblitz.io
Stackblitz代码示例:https://stackblitz.com/edit/ng2-file-upload-example
官方文档链接https://valor-software.com/ng2-file-upload/
根据上面的答案,我用Angular 5.x构建了这个
只需调用uploadFile(url, file).subscribe()来触发上传
import { Injectable } from '@angular/core';
import {HttpClient, HttpParams, HttpRequest, HttpEvent} from '@angular/common/http';
import {Observable} from "rxjs";
@Injectable()
export class UploadService {
constructor(private http: HttpClient) { }
// file from event.target.files[0]
uploadFile(url: string, file: File): Observable<HttpEvent<any>> {
let formData = new FormData();
formData.append('upload', file);
let params = new HttpParams();
const options = {
params: params,
reportProgress: true,
};
const req = new HttpRequest('POST', url, formData, options);
return this.http.request(req);
}
}
在组件中像这样使用它
// At the drag drop area
// (drop)="onDropFile($event)"
onDropFile(event: DragEvent) {
event.preventDefault();
this.uploadFile(event.dataTransfer.files);
}
// At the drag drop area
// (dragover)="onDragOverFile($event)"
onDragOverFile(event) {
event.stopPropagation();
event.preventDefault();
}
// At the file input element
// (change)="selectFile($event)"
selectFile(event) {
this.uploadFile(event.target.files);
}
uploadFile(files: FileList) {
if (files.length == 0) {
console.log("No file selected!");
return
}
let file: File = files[0];
this.upload.uploadFile(this.appCfg.baseUrl + "/api/flash/upload", file)
.subscribe(
event => {
if (event.type == HttpEventType.UploadProgress) {
const percentDone = Math.round(100 * event.loaded / event.total);
console.log(`File is ${percentDone}% loaded.`);
} else if (event instanceof HttpResponse) {
console.log('File is completely loaded!');
}
},
(err) => {
console.log("Upload Error:", err);
}, () => {
console.log("Upload done");
}
)
}
在Angular 2+中,让Content-Type为空是非常重要的。如果您将“内容类型”设置为“multipart/form-data”,则上传将无法工作!
upload.component.html
<input type="file" (change)="fileChange($event)" name="file" />
upload.component.ts
export class UploadComponent implements OnInit {
constructor(public http: Http) {}
fileChange(event): void {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file = fileList[0];
const formData = new FormData();
formData.append('file', file, file.name);
const headers = new Headers();
// It is very important to leave the Content-Type empty
// do not use headers.append('Content-Type', 'multipart/form-data');
headers.append('Authorization', 'Bearer ' + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9....');
const options = new RequestOptions({headers: headers});
this.http.post('https://api.mysite.com/uploadfile', formData, options)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(
data => console.log('success'),
error => console.log(error)
);
}
}
}
这是一个有用的教程,如何使用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));