【发布时间】:2019-08-29 02:10:57
【问题描述】:
我正在尝试通过网络浏览器上传文件,但我不能这样做。当我通过邮递员保存此 api 然后上传文件但我无法通过尝试网络浏览器上传文件。当我尝试通过网络浏览器上传文件时,我在服务器端收到类似“SyntaxError: Unexpected token - in JSON at position 0”之类的错误。
我使用 NodeJS,ExpressJs 作为后端,Angular 6 作为前端。
角度
html
<div>
<div>
<input type="file" (change)="createFormData($event)">
</div>
<button (click)="upload()">Upload</button>
</div>
ts
export class PhotographComponent implements OnInit {
selectedFile: File = null;
fd = new FormData();
constructor(private formBuilder: FormBuilder, private httpClient:
HttpClient) {}
ngOnInit() {}
createFormData(event) {
this.selectedFile = <File>event.target.files[0];
this.fd.append('photo', this.selectedFile, this.selectedFile.name);
}
upload() {
this.httpClient.post(environment.apiUrl + 'photographs', this.fd)
.subscribe( result => {
console.log(result);
});
}
}
NodeJs
const { Photograph, validate } = require('../models/photograph');
const multer = require('multer');
const express = require('express');
const router = express.Router();
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads')
},
filename: function (req, file, cb) {
cb(null, file.originalname)
}
})
const upload = multer({
storage: storage
})
// save photograph
router.post('/', upload.single('photo'), (req, res) => {
console.log(req.file);
const filename = req.file.filename;
const path = req.file.path;
res.json({message: 'File uploaded'});
})
module.exports = router;
请帮我找到上传文件的解决方案。 谢谢。
【问题讨论】:
-
这个错误发生在服务器端吗?还有你上传的文件大小是多少?
-
是的。当我通过邮递员保存此 api 然后上传文件但我无法通过尝试网络浏览器上传文件。当我尝试通过网络浏览器上传文件时,我在服务器端收到类似“SyntaxError: Unexpected token - in JSON at position 0”之类的错误。
-
我的文件大小只有45kb
-
您是否尝试过将客户端的请求标头显式设置为
enctype: multipart/form-data? -
不,我没有。我在 Auth Intercepter 中设置了标题('Content-Type': 'application/json')