简体   繁体   中英

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

Here's my Java code to upload a file to the Node.js 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 the Node.js code. I am using express framework on the Node.js 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 the Java code, the Node.js 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 help me with this?

req.files has been removed on Express 4+ version.

In Express 4, req.files is no longer available on the req object by default. To access uploaded files on the req.files object, use a multipart-handling middleware like busboy, multer, formidable, multiparty, connect-multiparty, or pez.

Express Documentation

You could replace your NodeJS code to use busboy as your parser.

Follow busboy code samples .

Probably your final solution would end like that:

var express = require('express');
var app = express();

var Busboy = require('busboy'),
    path = require('path'),
    fs = require('fs'); 

app.post('/upload', function(req, res)  {
    var busboy = new Busboy({ headers : req.headers });

    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        var dirname = "/workspace/museek-server";
        var newPath = dirname + "/uploads/";
        var saveTo = path.join(newPath, path.basename(fieldname));
        file.pipe(fs.createWriteStream(saveTo));
    });

    busboy.on('finish', function() {
      res.writeHead(200, { 'Response': 'Saved' });
      res.end("That's all folks!");
    });

    return req.pipe(busboy);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM