2

目前我正在捕捉相机的图像,这种 Base64 格式,我正在通过 ajax 发送。

xhr({
  uri: 'http://localhost:1337/file/upload',
  method: 'post',
  body:'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...'
}

0 个文件上传成功!

4

1 回答 1

1

这是一个很好的链接,它将指导您将图像从 Ajax 客户端发送到 ajax 服务器。

http://www.nickdesteffen.com/blog/file-uploading-over-ajax-using-html5

您可以阅读此sails 文档以在sails 服务器上接收文件:

http://sailsjs.org/documentation/reference/request-req/req-file

您可以按照以下示例进行操作:

Client side ( ajax ): 

var files = [];

$("input[type=file]").change(function(event) {
  $.each(event.target.files, function(index, file) {
    var reader = new FileReader();
    reader.onload = function(event) {  
      object = {};
      object.filename = file.name;
      object.data = event.target.result;
      files.push(object);
    };  
    reader.readAsDataURL(file);
  });
});

$("form").submit(function(form) {
  $.each(files, function(index, file) {
    $.ajax({url: "/ajax-upload",
          type: 'POST',
          data: {filename: file.filename, data: file.data}, // file.data is your base 64
          success: function(data, status, xhr) {}
    });      
  });
  files = [];
  form.preventDefault();
});

服务器端(sails):[假设你有一个带有 ID 和 URL 的模型图片] [这里是图片控制器的示例,只是为了给你一个想法]

module.exports = {
    uploadPicture: function(req, res) {

  req.file('picture').upload({
    // don't allow the total upload size to exceed ~10MB
    maxBytes: 10000000
  },
  function onDone(err, uploadedFiles) {


    if (err) {
      return res.negotiate(err);
    }
    // If no files were uploaded, respond with an error.
    if (uploadedFiles.length === 0){
      return res.badRequest('No file was uploaded');
    }



    // Save the "fd" and the url where the avatar for a user can be accessed
    Picture
      .update(777, { // give real ID
        // Generate a unique URL where the avatar can be downloaded.
        pictureURL: require('util').format('%s/user/pictures/%s', sails.getBaseUrl(), 777), // GIVE REAL ID
        // Grab the first file and use it's `fd` (file descriptor)
        pictureFD: uploadedFiles[0].fd
      })
      .exec(function (err){
        if (err) return res.negotiate(err);
        return res.ok();
      });
    });

  }
};

希望这对您的研究有所帮助。我还建议您先使用 Postman 测试您的 API,然后再编写您的客户端。

于 2016-03-07T13:57:00.277 回答