我尝试使用Angular 4上传图像,使用Multer库上传和Express。
这是我的route.js:
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'uploads')
},
filename: function(req, file, cb) {
cb(null, file.fieldname + '-' + Date.now() + '.jpg')
}
});
const upload = multer({ storage: storage }).single('avatar');
router.post('/upload_avatar', function(req, res) {
upload(req, res, function(err) {
if (err) {
// An error occurred when uploading
throw err;
}
res.json({
sucess: true,
message: 'Image was uploaded successfully'
});
// Everything went fine
})
});
如果我使用Postman它确实有效并将图像添加到我项目的uploads目录中。
这是我的UserService.js
import { Injectable } from '@angular/core';
import {Http, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
user: any;
filesToUpload: Array<File> = [];
constructor(private http: Http) { }
uploadAvatar(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();
/** No need to include Content-Type in Angular 4 */
// headers.append('Content-Type', 'multipart/form-data');
// headers.append('Accept', 'application/json');
this.http.post('http://localhost:3000/api/upload_avatar', formData,
{headers: headers})
.map(res => res.json())
.catch(function(err){
throw err;
})
.subscribe(
data => console.log('success'),
error => console.log(error)
)
}
}
我的profile.component.ts使用此功能:
fileChangeEvent(event) {
this.userService.uploadAvatar(event);
}
最后我的HTML看起来像这样:
<div class="col-md-4">
<img [src]="userImg" class="img-thumbnail" alt="">
<input type="file" (change)="fileChangeEvent($event)"
placeholder="Upload file..." />
<!-- <button type="button" (click)="upload()">Upload</button> --
>
</div>
当我使用邮差时它有效,所以我想这个问题与角度代码有关。 我认为它必须与标题或正文请求。 这是我从节点服务器得到的错误:
C:\Users\admin\Desktop\project\contactlist\routes\route.js:33
throw err;
^
Error: Unexpected field
at makeError
node_modules\multer\lib\make-
error.js:12:13)
at wrappedFileFilter
node_modules\multer\index.js:40:19)
at Busboy.<anonymous> \node_modules\multer\lib\make-middleware.js:114:7)
at emitMany (events.js:127:13)
at Busboy.emit (events.js:201:7)
at Busboy.emit node_modules\busboy\lib\main.js:38:33)
at PartStream.<anonymous> (
node_modules\busboy\lib\types\multipart.js:213:13)
at emitOne (events.js:96:13)
at PartStream.emit (events.js:188:7)
at HeaderParser.<anonymous> (node_modules\dicer\lib\Dicer.js:51:16)
at emitOne (events.js:96:13)
at HeaderParser.emit (events.js:188:7)
at HeaderParser._finish (node_modules\dicer\lib\HeaderParser.js:68:8)
at SBMH.<anonymous> (node_modules\dicer\lib\HeaderParser.js:40:12)
at emitMany (events.js:127:13)
at SBMH.emit (events.js:201:7)
答案 0 :(得分:0)
我使用以下代码:
fileChange(event) {
const fileList: FileList = event.target.files;
if (fileList.length > 0) {
const file: File = fileList[0];
const formData: FormData = new FormData();
formData.append('file', file, file.name);
const headers = new Headers();
headers.append('Content-Type', 'multipart/form-data');
headers.append('Accept', 'application/json');
const body = JSON.stringify({ headers: headers });
this.http.post('https://bla.com', formData, body)
.map(res => res.json())
.catch(error => Observable.throw(error))
.subscribe(data => {
const Response = data['_status'];
if (Response) {
this.uploadFile.push(data);
} else {
this.showFileError = data['_error'];
}
}
);
}
}
HTML的模板:
<input class="file-hide" type="file" (change)="fileChange($event)">
答案 1 :(得分:0)
刚刚改变了这一行:
formData.append('uploadFile', file, file.name);
为:
formData.append('avatar', file, file.name);
现在有效!