我在前端使用Angular 2,在后端使用Node.js。我正在尝试将文件上传到Azure存储Blob容器,但是在尝试将图像发送到api时始终出现错误。任何帮助将不胜感激,谢谢。
这是服务器端的错误:
contentType: files.myfile.type,
TypeError: Cannot read property 'type' of undefined
客户端错误
core.js:1521 ERROR
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
error
:
ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers
:
HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message
:
"Http failure response for (unknown url): 0 Unknown Error"
name
:
"HttpErrorResponse"
ok
:
false
status
:
0
statusText
:
"Unknown Error"
url
:
null
__proto__
:
HttpResponseBase
upload.component.ts
export class UploadComponent implements OnInit {
selectedFile: File = null;
onFileSelected(event) {
this.selectedFile = <File>event.target.files[0];
}
onUpload() {
const fd = new FormData();
fd.append('image', this.selectedFile, this.selectedFile.name);
this.http.post('http://localhost:3000/upload', fd , {
reportProgress : true,
observe: 'events'
}).subscribe( event => {
console.log(event);
});
}
constructor(private http: HttpClient) {}
ngOnInit() {
}
}
server.js
app.post('/upload', function(req, res) {
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
var options = {
contentType: files.myfile.type,
metadata: { fileName: files.myfile.name }
};
blobSvc.createBlockBlobFromLocalFile('images', files.myfile.name, files.myfile.path, options, function(error, result, response) {
if(!error){
// file uploaded
res.send('file uploaded!');
}
});
});
});
答案 0 :(得分:1)
如我所见,您传递给服务器的对象File为null,因此会引发上述错误。
您可以在chrome开发人员工具的“网络”标签上检查问题,并查看是否已选择文件。希望对您有所帮助。