我有快速服务器正在运行,我想上传没有html <input type="file">
标记的图片(<form>
)。这甚至可能吗?
我使用此函数在输入值变化时从输入中获取文件:
function readImage (input) {
var _URL = window.URL || window.webkitURL;
if (input.files && input.files[0]) {
var myImg = new Image();
myImg.onload = function () {
var img = {
image: myImg.src,
file: input.files[0],
w: this.width,
h: this.height
};
return img;
};
myImg.src = _URL.createObjectURL(input.files[0]);
}
}
答案 0 :(得分:1)
您可以尝试使用FormData API。这是一个使用jQuery的例子:
var data = new FormData();
data.append('image', input.files[0]);
$.ajax({
url: '/foo',
data: data,
contentType: false,
processData: false,
success: function(response) {
alert('Image uploaded!');
},
error: function(jqXHR, textStatus, errorMessage) {
alert('Error uploading: ' + errorMessage);
}
});
答案 1 :(得分:0)
客户端:
var image = $("#imageid")[0].files[0];
var formdata = new FormData();
formdata.append('image', image);
$.ajax({
url: '/uploads/',
data: formdata,
contentType: false,
processData: false,
type: 'POST',
'success':function(data){
alert(data);
}
});
服务器端: 使用multer
var express = require('express');
var router = express.Router();
var path = require("path");
var multer = require("multer");
var uploading = multer({
dest: './public/uploads/'
});
router.post('/', uploading.single('image'),function(req, res) {
console.log(req.file);
res.send(req.file);
});
module.exports = router;
输出: 服务器端:
{ fieldname: 'image',
originalname: 'Untitled.png',
encoding: '7bit',
mimetype: 'image/png',
destination: './public/uploads/',
filename: 'bde1b15ba5b62b4106f86b49c73720ea',
path: './public/uploads/bde1b15ba5b62b4106f86b49c73720ea',
size: 52375 }
希望这有帮助!