2

I'm trying to upload a file using jQuery Ajax + FormData object found on Chrome and Firefox browsers. The code I'm using to do it is the following:

var formData = new FormData();
    formData.append('image', $scope.image.data);

     $.ajax({
       url: '/wines/'+id+'/image',
       type: 'POST',
       data: formData,
        processData:false,
        contentType:false
     }).done(function(){
       $location.path('/');
     });

By looking at the developer tools I can see that the request is formed correctly, however express is recognising the contents inside req.body instead of req.files. Here is the request payload image:

Request payload

Express config:

app.configure(function(){
app.set('views', __dirname + '/app');
app.engine('.html', require('ejs').renderFile)
app.use(express.static(__dirname + '/app'));
app.use(express.bodyParser());
app.use(express.methodOverride());

app.use(app.router);
});

What's what I am doing wrong?? Thanks a lot.

0

1 Answer 1

1

Because its not a file, its just a string. To AJAX a file with FormData you have to pass a File object to FormData.append what you are passing is a data uri which is just a string.

A file in a multipart/form-data body looks something like this

------WebKitFormBoundaryNBylbsEYlWSsq2lB
Content-Disposition: form-data; name="image"; filename="999.jpg"
Content-Type: image/jpeg

The file content here
------WebKitFormBoundaryNBylbsEYlWSsq2lB--
Sign up to request clarification or add additional context in comments.

1 Comment

You're right, I was sending the FileReader result when I needed to send the raw file object

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.