Javascript XHR发送图像文件和字符串不工作
这看起来应该很简单,但我花了好几个小时才弄明白 我想发布一个带有字符串坐标的图像文件,以便在服务器端裁剪图像 以下是我的客户端代码:Javascript XHR发送图像文件和字符串不工作,javascript,express,xmlhttprequest,Javascript,Express,Xmlhttprequest,这看起来应该很简单,但我花了好几个小时才弄明白 我想发布一个带有字符串坐标的图像文件,以便在服务器端裁剪图像 以下是我的客户端代码: var formdata = new FormData(); formdata.append("file", file); formdata.append("coords", JSON.stringify(coordInfo)); var xhr = new XMLHttpRequest(); if (
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 my
中,请求有效负载类似于:
------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--
但是服务器端的日志只显示坐标
:
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}' }
我觉得我已经尝试了客户端和服务器端的每一种变体来实现这一点。之前,我使用AJAXHR请求和busboy服务器端解析请求。我会得到一个可以保存的文件对象,但当检索到它时,它会显示为一个损坏的图像
因此,现在我正在尝试一个非AJAX XHR,并使用connectmultiparty
作为解析,但仍然没有成功。文件应该位于req.files
中,而不是req.body
另外,您应该注意,req.body.coords
看起来像一个JSON字符串,而不是一个对象。您需要JSON.parse
it将其用作对象,以防万一它丢失了什么东西。OK,这样就解决了这个问题,但基本问题仍然存在,因为我正在以错误的格式保存图像。我们必须弄清楚这一点。