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

XHR sending image file and string not working

本文关键字:字符串 工作 文件 图像 XHR      更新时间:2023-09-26

这看起来应该很简单,但是我花了几个小时才弄明白。

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

下面是我的客户端代码:
      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服务器端来解析请求。我会得到一个文件对象,我可以保存,但当检索它会显示为一个破碎的图像。

这就是那个没有解决的S.O.问题。

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

文件应该在req.files而不是req.body

同样,不相关的是,您应该注意到req.body.coords看起来像一个JSON字符串,而不是一个对象。你需要JSON.parse来使用它作为一个对象,,以防它错过了