我有一个非常快速的问题:
我有一个img标签(在我的模板文件中),它包含一个图像,在我的Angular Controller中我打电话:
var image = document.getElementById('srcImage');
我想将此图像^发送到后端(我正在使用REST)。我将用于此POST方法的URL是: '/ API / V1 /图像/ addImage'
我已经尝试过ng-file-upload和$ http.post,但似乎没有任何效果。有什么方法可以简单地将此图像发送到服务器,以便将其存储在数据库或文件系统中吗?我愿意接受任何解决方案来实现这一目标。
谢谢!
答案 0 :(得分:2)
您可以使用以下库,它们也有很好的文档
前端 - https://github.com/nervgh/angular-file-upload
对于后端 - https://github.com/expressjs/multer
示例代码段 -
在HTML中:
<input type="file" nv-file-select="" uploader="ctrl.uploader" multiple />
角度控制器:
vm.uploader = new FileUploader({
url: 'http://' + SERVER_URL + '/upload',
formData: [{
id: 1
}]
});
vm.save = function() {
vm.uploader.onBeforeUploadItem = function (item) {
console.log(item);
/* some action */
};
vm.uploader.onSuccessItem = function (item, imgResponse, status, headers) {
console.log(item);
console.log(imgResponse);
console.log(status);
console.log(headers);
/* some action */
};
};
节点服务器:
var fs = require('fs');
var multer = require('multer');
var fileName = '';
var storage = multer.diskStorage({
destination: function (req, file, cb) {
var dirPath = 'path/to/save/file'
if (!fs.existsSync(dirPath)) {
var dir = fs.mkdirSync(dirPath);
}
cb(null, dirPath + '/');
},
filename: function (req, file, cb) {
var ext = file.originalname.substring(file.originalname.lastIndexOf("."));
fileName = Date.now() + ext;
cb(null, fileName);
}
});
// Assuming Express -
app.get('/upload', function (req, res) {
var upload = multer({
storage: storage
}).array('file', 12);
upload(req, res, function (err) {
if (err) {
// An error occurred when uploading
res.json(err);
}
res.json(fileName);
});
});
答案 1 :(得分:0)
You can try multipart/form-data
like this:
<form id = "uploadForm"
enctype = "multipart/form-data"
action = "/api/photo"
method = "post"
>
<input type="file" name="userPhoto" />
<input type="submit" value="Upload Image" name="submit">
</form>