【问题标题】:How can I read data sent from form using FormData with ajax and store it to local folder?如何使用带有 ajax 的 FormData 读取从表单发送的数据并将其存储到本地文件夹?
【发布时间】:2015-07-03 15:27:18
【问题描述】:

这是我在客户端的 ajax 代码:

$('#btn_file').on('change', function(e){
        e.preventDefault();            
        var data = new FormData();
        data.append('photo', $('#btn_file')[0].files[0]);

        $.ajax({
            url: "/media/images",
            type: "POST",
            data: data,
            processData: false,
            contentType: false,
            success: function (data) {
                console.log(data);
            }
        });
    return false;
 });

这是我的服务器端:

app.post('/media/images', function (req, res) {
   //What do I have to do to get an image and save it? And how do I rename the file?

});

HTML:

<form id="send_image" ction=”/media/images” method=”post” enctype=”multipart/form-data”>
     <input type="file" name="photo" id="btn_file"/>
</form> 

我找到了一些示例,但没有一个有效。我真的不知道问题出在哪里。谢谢。

【问题讨论】:

    标签: javascript jquery ajax node.js multipartform-data


    【解决方案1】:

    在 Node JS 中可以使用 Formidable 来管理文件上传:https://www.npmjs.com/package/formidable#readme

    var formidable = require('formidable');
    app.post('/media/images', function (req, res) {
        var form = new formidable.IncomingForm();
    
        form.parse(req, function(err, fields, files) {
          res.writeHead(200, {'content-type': 'image/jpeg'});
          res.write('received upload:\n\n');
          res.end(util.inspect({fields: fields, files: files}));
        });
    });
    

    然后你可以使用“fs”api来存储文件。

    【讨论】:

    • 太棒了!它就像一个魅力!我找到了一个强大的例子,但我无法让它工作!谢谢你!我可以在 fs 方面获得更多帮助吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-30
    • 2019-09-06
    • 2021-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多