1

I am trying to upload a file from andriod application, using Jquery to node.js using express..

My client side code is:

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.')
          },
        })
      }

I have used post form without any content type because if i use multipart/form-data it says error about boundary ..

my server side code using node.js is:

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)
    }
    )
}

when the file comes to server, it gives an error of res.files.file is undefined ..

I have searched alot of forums, they say that res.files.file is only access when contenttype is multipart/form-data but then the boundary problem occurs

Any help on that is highly appreciated

4

2 回答 2

0

Boundary is a special sequence of characters that separates your binary data.

You should submit MIME type as multipart/form-data, as well as set your imagedata to FormData() type (from your snippet it's not clear if it is FormData type).

Here are similar issues and solutions:

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?

于 2013-06-21T20:38:36.813 回答
0

A great alternative to writing this code is to use filepicker.io This allows you to connect to yoru own s3 bucket. When the file is saved, you get back a callback with the S3 url, you can then simply pass that url to your node api, and save it. I have used this to avoid having to write extra server code for handling file uploads. Extra bonus, if you need to do this with images, and want users to be able to edit the images, you can use Aviary which allows an image to be edited locally, and you then get back another s3 url, that you can then save to your server..

于 2013-06-21T21:18:51.517 回答