trigoman
trigoman

Reputation: 3715

Node.js server using Express.js uploaded file name

Some background: I'm trying to create a web service using node.js and express that accepts a POST request with an image attached.

I have been able to send the request successfully, but I want to be able to do something with the image. All of the examples that I've seen with that do this use a form to upload a file using POST, doing so, allows them to give a name to the file that they are going to upload. Allowing them to do the following

app.post('/upload',function(req,res) {
    req.files.formName // have access to the file's information
}

I just want to be able to create a POST request in REST-like way, so the file gets upload via an API call so when the file gets to the server, express gives it a random name and the way to access the file in the files array is to use the actual pictures filename, which depends on what the user's filename is and I can't make that constant.

app.post('/upload',function(req,res) {
    req.files.<what goes here>
    req.files[0] // this wont work
}

Your help is appreciated, and if I'm doing this the wrong way, say using express is a bad choice, then please go ahead and suggest. I'm doing this project to learn how to use node.js and all of it's goodness.

Upvotes: 3

Views: 3813

Answers (3)

IvanM
IvanM

Reputation: 3053

for simple uploading you just need these configuration:

app.use(express.static(__dirname + '/upload'));
app.use(express.bodyParser({uploadDir:__dirname + '/upload'}));

and in jade template:

form(method='post', action='/upload', enctype='multipart/form-data')
    input(name='file', type='file')
    input(type='submit')

Upvotes: 0

robertklep
robertklep

Reputation: 203304

If you want access to the raw HTTP body:

app.post('/upload', function(req, res) {
  var chunks = '';
  req.on('data', function(data) {
    chunks += data;
  });
  req.on('end', function() {
    console.log('received', chunks.length, 'bytes', chunks);
    res.send(...);
  });
});

(if you need to use express.bodyParser as well, make sure you app.use() that after setting the above route)

Upvotes: 0

scartag
scartag

Reputation: 17680

It still works the same way.

Even if you are sending the POST in a REST-like way, you still have to name the parameters in your api call.

if for instance you've named the picture 'image'.

var data = {"image":imageData};

To access it is still

req.files.image

Upvotes: 1

Related Questions