如何在nodejs中使用请求模仿上传图片

时间:2014-07-11 01:13:09

标签: node.js image-uploading web-crawler

我想用模块请求模仿上传图片,我通过Chrome网络获取请求rayload:

------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="Filename"

2033103.jpg
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="FileType"

Image
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="N"

1
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="F"

MemberIDCard
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="fileext"

*.jpg;*.png;*.gif
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="folder"

/Transport/
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="Filedata"; filename="2033103.jpg"
Content-Type: application/octet-stream


------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3
Content-Disposition: form-data; name="Upload"

Submit Query
------------Ef1cH2gL6GI3ae0ei4Ef1cH2gL6GI3--

,我的代码是这样的:

request.post({
    uri: url,
    headers: {
        'content-type' : 'application/octet-stream'
    },
    form: {
        Filename: '2000.jpg',
        FileType: 'Image',
        N: 1,
        F: 'MemberIDCard',
        fileext: '*.jpg;*.png;*.gif',
        folder: '/Transport/',
        Upload: 'Submit Query'
    },
    body: 'http://t1.qpic.cn/mblogpic/bc65fe3404f5084b2d7e/2000.jpg'
}, function (error, response, body) {
    if (!error) {
        console.log(body);
    }
});

但似乎不起作用,我该怎么做模仿这个上传图片?

2 个答案:

答案 0 :(得分:0)

如果您使用form选项的文字对象,则会将表单发送为application/x-www-form-urlencoded。您需要做的是use the FormData API发送multipart/form-data

var r = request.post({
    uri: url
}, function (error, response, body) {
    if (!error) {
        console.log(body);
    }
});
var form = r.form()
form.append('Filename', '2000.jpg');
form.append('FileType', 'Image');
form.append('N', '1');
form.append('F', 'MemberIDCard');
form.append('fileext', '*.jpg;*.png;*.gif');
form.append('folder', '/Transport/');
form.append('Filedata', request('http://t1.qpic.cn/mblogpic/bc65fe3404f5084b2d7e/2000.jpg'));
form.append('Upload', 'Submit Query');

答案 1 :(得分:0)

,我使用needle模块,代码如下:

var buffer = fs.readFileSync('xxxx.png');

var data = { 
    Filename: 'xxxx.png', 
    FileType: 'Image', 
    N: 1, 
    F: 'MemberIDCard', 
    fileext: '.jpg;.png;*.gif', 
    folder: '/Transport/', 
    Upload: 'Submit Query', 
    Filedata: { 
        buffer : buffer, 
        filename : 'xxxx.png', 
        content_type : 'application/octet-stream' 
    } 
}

needle.post(uri, data, { multipart: true }, function(err, resp, body) {
    //do something... 
});