简体   繁体   English

使用Ajax将文件上传到Node.js

[英]File upload to nodejs using ajax

I am trying to upload image to nodejs server using ajax but it fails to get file. 我正在尝试使用ajax将图像上传到nodejs服务器,但无法获取文件。

Client Side 客户端

function sendFileToServer(file){
    var formData = new FormData();
    formData.append('profile_image',file,file.name);
    $.ajax({
        type: "POST",
        url: "URL",
        data: formData,
        dataType:'json',
        processData: false,
        success: function (data) {

            alert("Data Uploaded: "+data);
        },
        error : function(err){
            alert(JSON.stringify(err));
        }
    });
}
$("#profile_image_2").change(function(){
    var file = this.files[0];
    sendFileToServer(file);
});

Server Side 服务器端

var multer  = require('multer');
var mime = require('mime-lib');
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './public/upload/')
    },
    filename: function (req, file, cb) {
        console.log("filename exte "+file.mimetype);
        console.log(mime.extension(file.mimetype));
        cb(null, Date.now() + '.' + mime.extension(file.mimetype)[0]);
        //crypto.pseudoRandomBytes(16, function (err, raw) {
        //    cb(null, raw.toString('hex') + Date.now() + '.' + mime.extension(file.mimetype));
        //});
    }
});
var uploading = multer({ storage: storage });
router.post('/profile',uploading.single('profile_image') ,function(req,res){

    if (req.file){
        res.json("In here");

    }else{
        res.json("FILE DOES NOT EXIST");//ALWAYS ENDS UP HERE
    }

});

When i try it in bare form it works fine, but not using ajax. 当我以裸露形式尝试时,它可以正常工作,但不能使用Ajax。 Please help 请帮忙

Try to use jQuery Form Plugin . 尝试使用jQuery Form Plugin It will make this for you. 它将为您做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM