I'm trying to make a file upload working in a angular project with a node server
Angular:
public uploadFile(file: File): Observable<any> {
const formData: FormData = new FormData();
formData.append('file', file, file.name);
return this.http.post<any>(environment.api_url + '/upload', formData);
}
Nodejs
function upload(req, res){
var dir = __dirname +'/../uploaded';
var fileDir;
if (!fs.existsSync(dir)){
fs.mkdirSync(dir);
}
var form = new IncomingForm({ uploadDir: __dirname + '/../uploaded' });
let readStream;
form.on('file', (field, file) => {
fs.renameSync(file.path, file.path + '_' + file.name);
fileDir = file.path + '_' + file.name;
fileDir = fileDir.replace(__dirname, '');
});
form.on('end', () => {
dirname = path.join(__dirname, '/../uploaded');
fileDir = fileDir.replace(dirname + '\\', '');
fileDir = fileDir.replace('/app/src/uploaded/', '');
return res.status(200).json({ 'file': fileDir }).end();
});
form.parse(req);
}
When I submit a form I get the error :
events.js:167
throw er; // Unhandled 'error' event
^
SyntaxError: Unexpected number in JSON at position 1
at JSON.parse (<anonymous>)
I can't find the source of the problem I tried different approaches on the client side and the server side. There is a problem with the JSON data but I don't have a way to modify it with this file upload,
Hope anybody has a solution
Can you please try the above code by placing this line of code
form.parse(req);
after this line
var form = new IncomingForm({ uploadDir: __dirname + '/../uploaded' });
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.