将图像从JQuery上传到Node JS [英] Upload image from JQuery to Node JS
问题描述
我需要从我的 HTML
页面上传图片文件。不过,我不打算使用表单
标记,因为还有其他表单
字段(文本框,复选框等)将被用于稍后将数据传递到服务器。
I need to upload an image file from my HTML
page. However, I am not going to use the form
tag since there are other form
fields (textfields, checkbox etc) that will be used to pass data to the server later.
我的后端位于 Node JS
中。所有我想要的是从 Node Js
结束检索图像数据(文件)。我怎样才能做到这一点
My back end is in Node JS
. All what I want is to retrieve the image data (file) from the Node Js
end. How can I do this
HTML
<div class="container">
<div class="row">
<div class="col-xs-12">
<div class="panel panel-default">
<div class="panel-body">
<span class="glyphicon glyphicon-cloud-upload"></span>
<h2>File Uploader</h2>
<h4>coligo.io</h4>
<div class="progress">
<div class="progress-bar" role="progressbar"></div>
</div>
<button class="btn btn-lg upload-btn" type="button">Upload File</button>
</div>
</div>
</div>
</div>
</div>
<input id="upload-input" type="file" name="uploads" multiple="multiple"></br>
JQuery
JQuery
$('.upload-btn').on('click', function (){
$('#upload-input').click();
$('.progress-bar').text('0%');
$('.progress-bar').width('0%');
});
$('#upload-input').on('change', function(){
var files = $(this).get(0).files;
if (files.length > 0){
// create a FormData object which will be sent as the data payload in the
// AJAX request
var formData = new FormData();
// loop through all the selected files and add them to the formData object
for (var i = 0; i < files.length; i++) {
var file = files[i];
var tmppath = URL.createObjectURL(event.target.files[0]);
// add the files to formData object for the data payload
formData.append('uploads', tmppath);
}
$.ajax({
url: '/myp/imgup',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data){
console.log('upload successful!\n' + data);
},
xhr: function() {
// create an XMLHttpRequest
var xhr = new XMLHttpRequest();
// listen to the 'progress' event
xhr.upload.addEventListener('progress', function(evt) {
if (evt.lengthComputable) {
// calculate the percentage of upload completed
var percentComplete = evt.loaded / evt.total;
percentComplete = parseInt(percentComplete * 100);
// update the Bootstrap progress bar with the new percentage
$('.progress-bar').text(percentComplete + '%');
$('.progress-bar').width(percentComplete + '%');
// once the upload reaches 100%, set the progress bar text to done
if (percentComplete === 100) {
$('.progress-bar').html('Done');
}
}
}, false);
return xhr;
}
});
}
});
NODE JS
router.post('/imgup', function(req, res){
console.log(' File name '+req.files.upload);
});
我已经试了几天,没有运气。有人可以帮我解决问题。
I have been trying this out for several days, with no luck. Can someone help me out.
推荐答案
使用 multer
模块的示例:
var express = require("express");
var multer = require('multer');
var app = express();
app.get('/',function(req,res){
res.sendFile(__dirname + "/index.html");
});
var storage = multer.diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads');
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '-' + Date.now());
}
});
app.post('/api/file',function(req,res){
var upload = multer({ storage : storage}).single('userFile');
upload(req,res,function(err) {
if(err) {
return res.end("Error uploading file.");
}
res.end("File is uploaded");
});
});
app.listen(3000,function(){
console.log("Working on port 3000");
});
强大的
模块的例子:
var formidable = require('formidable'),
http = require('http'),
util = require('util');
http.createServer(function(req, res) {
if (req.url == '/upload' && req.method.toLowerCase() == 'post') {
// parse a file upload
var form = new formidable.IncomingForm();
form.parse(req, function(err, fields, files) {
if (err)
do-smth; // process error
// Copy file from temporary place
// var fs = require('fs');
// fs.rename(file.path, <targetPath>, function (err) { ... });
// Send result on client
res.writeHead(200, {'content-type': 'text/plain'});
res.write('received upload:\n\n');
res.end(util.inspect({fields: fields, files: files}));
});
return;
}
// show a file upload form
res.writeHead(200, {'content-type': 'text/html'});
res.end(
'<form action="/upload" enctype="multipart/form-data" method="post">'+
'<input type="text" name="title"><br>'+
'<input type="file" name="upload" multiple="multiple"><br>'+
'<input type="submit" value="Upload">'+
'</form>'
);
}).listen(8080);
摘自 Node.js -
文件上传。原作者是冰人, Aikon Mogwai 和 Mikhail 。可以在撰稿人中找到归因详情页面。该源根据 CC BY-SA 3.0 进行许可,可在< a href =https://archive.org/details/documentation-dump.7z =nofollow noreferrer>文档档案。参考主题ID:4080。
Excerpted from Node.js - File upload. The original authors were Iceman, Aikon Mogwai and Mikhail. Attribution details can be found on the contributor page. The source is licenced under CC BY-SA 3.0 and may be found in the Documentation archive. Reference topic ID: 4080.
这篇关于将图像从JQuery上传到Node JS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!