我有一个简单的.html
代码段:
<input id="cin" name="cin" type="file" placeholder="Upload a file..." />
单击输入旁边的按钮时,此功能称为:
upload() {
let inputEl: HTMLInputElement = <HTMLInputElement>(
document.getElementById("cin")
);
let formData = new FormData();
formData.append("file", inputEl.files.item(0));
console.log(inputEl.files.item(0));
console.log(formData);
this.uploadService
.uploadFile(formData)
.subscribe(files => console.log("files", files));
}
这是引用服务中的uploadFile方法的代码:
export class UploadService {
constructor(private http: HttpClient, private loginService: LoginService) {}
httpOptions = {
headers: new HttpHeaders({
"Content-Type": "application/x-www-form-urlencoded",
"x-access-token": this.loginService.userInfo
})
};
uploadFile(file): Observable<any> {
console.log(file);
return this.http.post<any>(
"http://localhost:8080/nodec3/api/v1/uploadFile",
{
image: file
},
this.httpOptions
);
}
}
以下是我的NodeJS代码:
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, "./files/");
},
filename: function(req, file, cb) {
cb(
null,
file.originalname.split(".")[0] +
Date.now() +
"." +
mime.getExtension(file.mimetype)
);
}
});
var upload = multer({ storage: storage });
module.exports.upload = upload;
和路线:
router.post(
"/uploadFile",
verifyToken,
fileController.upload.single("image"),
(req, res, next) => {
console.log(req);
res.status(201).send("File uploaded");
}
);
使用Postman附加文件时,nodejs使用其表单数据将文件正确存储在硬盘中。但是,使用上面的Angular代码,虽然它不会打印出任何错误,但不会保存文件。有人知道为什么会发生这种情况吗?
谢谢!