jeudi 5 novembre 2015

How can I upload file on nodejs server with Java? (REST API)

Here's my java code to upload file to nodejs server.

import java.io.File;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.util.EntityUtils;


public class PostFile {
    public static void main(String[] args) throws Exception {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost("http://127.0.0.1/upload");
        File file = new File("/Users/KHC/test.txt");

        MultipartEntity mpEntity = new MultipartEntity();

        ContentBody cbFile = new FileBody(file);
        mpEntity.addPart("userfile", cbFile);



        httppost.setEntity(mpEntity);
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println(EntityUtils.toString(resEntity));
        }if (resEntity != null) {
            resEntity.consumeContent();
        }

        httpclient.getConnectionManager().shutdown();
    }
}

And this is nodejs code. I am using express framework on nodejs server.

var fs = require('fs');


module.exports = function(app) {


app.get('/',function(req,res){
    res.end("Node-File-Upload");

});
app.post('/upload', function(req, res) {
    console.log(req.files);
    //console.log(req.files.userfile.originalFilename);
    //console.log(req.files.userfile.path);
    fs.readFile(req.files.userfile.path, function (err, data){
    var dirname = "/workspace/museek-server";
    var newPath = dirname + "/uploads/" +   req.files.image.originalFilename;
    fs.writeFile(newPath, data, function (err) {
    if(err){
    res.json({'response':"Error"});
    }else {
    res.json({'response':"Saved"});
}
});
});
});
};

When I execute java code, the nodejs server cannot read req.files because req.files is undefined. I think there is another way to read multipart file.. But I cannot find it on the Internet. Can anyone give answer for this?

Aucun commentaire:

Enregistrer un commentaire