【问题标题】:Upload using XMLHttpRequest not working on mobile使用 XMLHttpRequest 上传无法在移动设备上运行
【发布时间】:2016-07-27 23:24:24
【问题描述】:

大家好,我目前正在开发使用 XMLHttpRequest 的上传功能。它在网络浏览器上完美运行,但当我在移动设备上测试它时,它不再工作了。这是在手机上选择照片后的错误日志:

E/chromium(2604): [ERROR:layer_tree_host_impl.cc(2121)] 强制 缺少工作上下文的零拷贝切片初始化

我已经添加了人行横道

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

if(fileInfo.size <= 20000000) {
    var xhr = new XMLHttpRequest();
    xhr.open('POST', '/uploadSomeWhere', true);
    xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
    if (xhr.upload) {
      xhr.upload.onprogress = function(e) {
        if (e.lengthComputable) {
          display.innerText = Math.floor((e.loaded / e.total) * 100) + '%';
          bootstrapPB.style.width = Math.floor((e.loaded / e.total) * 100) + '%';
        }
      }
      xhr.upload.onloadstart = function() {
        display.innerText = '0%';
        bootstrapPB.style.width = '0%';
      }
    }
    xhr.send(fileInfo);
} else {
  LocalState.set("mainError", "Please upload a file not more than 20MB");
}

在我的服务器中:

WebApp.connectHandlers.use('/uploadSomeWhere',function(req,res){
  function makeid()
  {
      var text = "";
      var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

      for( var i=0; i < 10; i++ )
          text += possible.charAt(Math.floor(Math.random() * possible.length));

      return text;
  }

  var uniquePhotoId = makeid();
  var originalPhoto = "/"+uniquePhotoId+"_original/";
  fs.mkdirSync("/home/dating/contents/"+originalPhoto);
  var file2 = fs.createWriteStream("/home/dating/contents"+originalPhoto+uniquePhotoId);

  file2.on('error',function(error){if(error){
    throw new Meteor.Error("Filed to upload image");
  }});
  file2.on('finish',function(){
      res.writeHead(200, {"content-type":"text/html"});
      res.end();
  });

  req.pipe(file2);

  // Set timeout to fully capture and convert the image
  setTimeout(function(){
   imageMagick(file2.path).autoOrient().setFormat("jpg").write(file2.path, function(){
     req.pipe(file2);
   });
  }, 1000);

  req._events.close;
});

请告知哪里出了问题。非常感谢。顺便说一句,我正在使用 ReactJS 和 Meteor 创建一个混合移动应用程序。

我不确定是 xhr 没有发送数据还是服务器没有 接受来自 xhr 的发送数据

【问题讨论】:

  • 我尝试添加代码xhr.onreadystatechange = function() { if (xhr.readyState === 4) { if (xhr.status === 200) { console.log('successful'); } else { console.log('failed'); } } } 以查看xhr.send() 是否成功发送并且它确实等于200,因此它可以正常执行。但是手机上没有上传任何东西
  • 我不确定是 xhr 没有发送数据还是服务器不接受来自 xhr 的发送数据。

标签: javascript mobile xmlhttprequest


【解决方案1】:

似乎在 reactjs 中使用 xhr 确实存在问题,所以我要做的就是使用 FileReader 将图像从文件输入转换为缓冲区 base64,然后我使用服务器中的 FS 节点将缓冲区 base64 转换为图片然后上传到目录。

现在一切都很好:)

【讨论】:

    猜你喜欢
    • 2021-11-05
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 2017-01-28
    • 2016-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多