使用XMLHttpRequest上传无法在移动设备上运行

使用XMLHttpRequest上传无法在移动设备上运行

本文介绍了使用XMLHttpRequest上传无法在移动设备上运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,我目前正在使用XMLHttpRequest的上载功能.它可以在Web浏览器上完美运行,但是当我在移动设备上对其进行测试时,它不再起作用.这是在手机上选择照片后的错误日志:

Hi guys I am currently working on an Upload feature that uses XMLHttpRequest. It works perfectly on web browsers but when I tested it on mobile it does not work anymore. Here is the error log after selecting photo on mobile:

我已经添加了人行横道

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

Here is my code on the client:

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创建一个混合移动应用程序.

Please advise what went wrong. Thanks a lot. By the way I am creating a hybrid mobile app using ReactJS and Meteor.

推荐答案

似乎在reactjs中使用xhr确实存在问题,因此我进行的整理工作是使用FileReader将图像从文件输入转换为缓冲区base64,然后从在那里,我在服务器中使用FS节点将缓冲区base64转换为图像,然后将其上传到目录.

It seems there is really an issue using xhr in reactjs so what I did to sort things out is use FileReader to convert image from file input to buffer base64 and from there I use FS node in the server to convert the buffer base64 to image then upload it to the directory.

现在一切都很好:)

这篇关于使用XMLHttpRequest上传无法在移动设备上运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 13:29