我正在开发基于Sails JS框架的前端。 我有个人资料页面,用户可以上传他们的新照片。头像将通过API发送到服务器。但是当我使用Sails的上传功能时,图像只保存在前端文件夹中。 谁能指导我怎么做?使用Ajax perharps
[更新]
<form method="POST" action="/profile/upload" enctype="multipart/form-data">
<input name="avatar" type="file">
<input type="submit" value="Send">
</form>
我做到了,但也许是最糟糕的做法:
这是提交上面表格时的功能工具
const UpdateProfileAvatar = (req, res) => {
// Rename the file with new random name
let fileName = Math.random().toString(36).substr(2,5) +".jpg";
// 2*** Save image to a folder in folder
req.file('avatar').upload({
maxBytes: 3*1024*1024, // limit 3MB
saveAs: fileName,
dirname: require('path').resolve(sails.config.appPath, 'assets/uploads')
}, function whenDone(err, uploadedFile) {
// 3*** Resize the image
// 4*** Send the image throught API
var request = require('request-promise');
request.post({
url: "https://api-link/user/avatar",
formData: {
avatar: fs.createReadStream('./assets/uploads/'+fileName)
},
headers: {
token: req.session.token
}
})
.then( result => {
console.log(result);
fs.unlinkSync('./assets/uploads/'+fileName);
return res.redirect('/profile');
})
.catch(err => {
console.log(err);
});
})