XHR发送图像文件和字符串不起作用

时间:2014-08-24 01:08:04

标签: javascript express xmlhttprequest

这似乎应该是如此简单,但需要花费数小时才能弄明白。

我想发布一个图像文件和字符串坐标,以便我可以裁剪服务器端的图像。

这是我的客户端代码:

      var formdata = new FormData();
      formdata.append("file", file);
      formdata.append("coords", JSON.stringify(coordInfo));

      var xhr = new XMLHttpRequest();
      if ( xhr.upload ) {

            // for handling the progress of the upload
            xhr.upload.addEventListener('progress',progressHandlingFunction, false); 
      }
      xhr.onreadystatechange = function(e) {
          if ( 4 == this.readyState ) {
              console.log(['xhr upload complete', e]);
          }
      };
      xhr.open('post', '/changeProfilePicture', true);
      xhr.setRequestHeader('X-Requested-With','XMLHttpRequest');
      xhr.send(formdata);

我的相关Express中间件是:

var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use('/changeProfilePicture', multipartMiddleware);

在我的路线中,我只是记录值以查看它们是否通过了:

    console.log("req.body.file");
    console.log(req.body.file);
    console.log("req.body.coords");
    console.log(req.body.coords);
    console.log("req.body.formdata");
    console.log(req.body.formdata);
    console.log("req.body");
    console.log(req.body);

在Chrome中我的request payload看起来像是:

------WebKitFormBoundary6A5RYri63wa7LqdB
Content-Disposition: form-data; name="file"; filename="monkey_mad.jpg"
Content-Type: image/jpeg


------WebKitFormBoundary6A5RYri63wa7LqdB
Content-Disposition: form-data; name="coords"

{"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}
------WebKitFormBoundary6A5RYri63wa7LqdB--

但是服务器端的日志只显示coords

17:53:19 web.1  | req.body.file
17:53:19 web.1  | undefined
17:53:19 web.1  | req.body.coords
17:53:19 web.1  | {"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}
17:53:19 web.1  | req.body.formdata
17:53:19 web.1  | undefined
17:53:19 web.1  | req.body
17:53:19 web.1  | { coords: '{"x":110.13333333333334,"y":103.841059602649,"x2":560,"y2":550.728476821192,"w":449.8666666666667,"h":446.887417218543}' }

我觉得我已尝试过每个变种都有客户端和服务器端来实现这一点。以前我使用AJAX XHR请求和busboy服务器端来解析请求。我会得到一个我可以保存的文件对象但是当它被检索时它将显示为一个损坏的图像。

Here's that S.O. question which is unresolved.

所以现在我正在尝试使用非AJAX XHR并使用connect-multiparty作为解析,但仍然没有运气。

1 个答案:

答案 0 :(得分:0)

文件应位于req.files而不是req.body

另外,不相关的,你应该注意req.body.coords看起来像一串JSON,而不是一个对象。您需要JSON.parse将其用作对象,以防万一丢失