【问题标题】:upload image file from jquery to node.js将图像文件从 jquery 上传到 node.js
【发布时间】:2013-05-22 02:24:15
【问题描述】:

我正在尝试使用 jquery 将文件从 Android 应用程序上传到 node.js 使用 express..

我的客户端代码是:

function uploadData(win) {
        var padI = imagedata.length-1
        while( '=' == imagedata[padI] ) {
          padI--
        }
        var padding = imagedata.length - padI - 1
        var user = load('user')
        $.ajax({
          url:'http://'+server+'/lifestream/api/user/'+user.username+'/upload', 
            type:'POST',
            contentType: false,
          processdata:false,
          data:imagedata, 
          success:win,
          error:function(err){
            showalert('Upload','Could not upload picture.')
          },
        })
      }

我使用了没有任何内容类型的 post 表单,因为如果我使用 multipart/form-data 它会显示关于边界的错误 ..

我使用 node.js 的服务器端代码是:

function upload(req,res) {

    var picid=uuid()
  console.log('Got here..' + __dirname)
  //console.log('Image file is here ' + req.files.file.path)
 // console.log('local name: ' + req.files.file.name)
  var serverPath = __dirname+'/images/' + picid+'.jpg'
   fs.rename(
    req.files.file.path,
    serverPath,
    function(error) {
      if (error) {
        console.log('Error '+error)
        res.contentType('text/plain')
        res.send(JSON.stringify({error: 'Something went wrong saving to server'}))
        return;
      }           
    // delete the /tmp/xxxxxxxxx file created during download
    fs.unlink(req.files.file.path, function() { })
    res.send(picid)
    }
    )
}

当文件到达服务器时,它会报错 res.files.file is undefined ..

我搜索了很多论坛,他们说 res.files.file 仅在 contenttype 为 multipart/form-data 时才可以访问,但随后出现边界问题

非常感谢任何帮助

【问题讨论】:

  • 我查看了那个网站,问题是它从浏览器生成客户端请求,所以它会包含边界变量,但是当我从 jquery ajax 生成它时会出错。跨度>

标签: android node.js jquery


【解决方案1】:

边界是分隔二进制数据的特殊字符序列。

您应该将 MIME 类型提交为 multipart/form-data,并将您的 imagedata 设置为 FormData() 类型(从您的 sn-p 不清楚它是否是 FormData 类型)。

以下是类似的问题和解决方案:

How to set a boundary on a multipart/form-data request while using jquery ajax FormData() with multiple files

jQuery AJAX 'multipart/form-data' Not Sending Data?

【讨论】:

    【解决方案2】:

    编写此代码的一个很好的替代方法是使用 filepicker.io 这允许您连接到 yoru 自己的 s3 存储桶。保存文件后,您会返回一个带有 S3 url 的回调,然后您可以简单地将该 url 传递给您的节点 api,并保存它。我用它来避免编写额外的服务器代码来处理文件上传。额外的好处,如果您需要对图像执行此操作,并且希望用户能够编辑图像,您可以使用Aviary 允许在本地编辑图像,然后您可以返回另一个 s3 url,您可以然后保存到您的服务器..

    【讨论】:

      猜你喜欢
      • 2014-07-03
      • 1970-01-01
      • 2020-07-10
      • 2020-06-12
      • 2016-04-28
      • 2020-12-30
      • 2016-12-01
      • 2013-08-27
      • 1970-01-01
      相关资源
      最近更新 更多