使用带有node.js服务器的java上传。 req.files为空

时间:2016-05-10 18:56:50

标签: java node.js express upload server

我尝试使用javaFX将文件上传到node.js服务器

此代码用于node.js服务器上传我的文件。

简化了我的代码。

var express = require('express');
var path = require('path');
var logger = require('morgan');
var methodOverride = require('method-override');
var app      = express();
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
var argv = require('optimist').argv;
var fs = require('fs');
app.use('/js', express.static(__dirname + '/js'));
app.use(morgan('dev'));
app.use(methodOverride());
app.use(bodyParser({keepExtensions:true,uploadDir:path.join(__dirname,'/files')}));
var busboy = require('connect-busboy');
app.use(busboy()); 
var fileupload = require('fileupload').createFileUpload('/home/kimmj8409/Myweb_front_end').middleware
app.post('/upload', fileupload, function(req, res) {
    res.send(req.body);
})

app.listen(8080, argv.fe_ip);
console.log("App listening on port 8080");

并且与此node.js服务器连接是javacode

MultipartUtility.java

public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;


public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true);
    httpConn.setDoInput(true);
    httpConn.setRequestProperty("Content-Type",
            "multipart/form-data; boundary=" + boundary);
    httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
    httpConn.setRequestProperty("Test", "Bonjour");
    outputStream = httpConn.getOutputStream();
    writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),
            true);
}

public void addFormField(String name, String value) {
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append("Content-Disposition: form-data; name=\"" + name + "\"")
            .append(LINE_FEED);
    writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
    writer.append(LINE_FEED);
    writer.append(value).append(LINE_FEED);
    writer.flush();
}

public void addFilePart(String fieldName, File uploadFile)
        throws IOException {
    String fileName = uploadFile.getName();
    writer.append("--" + boundary).append(LINE_FEED);
    writer.append(
            "Content-Disposition: form-data; name=\"" + fieldName
                    + "\"; filename=\"" + fileName + "\"")
            .append(LINE_FEED);
    writer.append(
            "Content-Type: "
                    + URLConnection.guessContentTypeFromName(fileName))
            .append(LINE_FEED);
    writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
    writer.append(LINE_FEED);
    writer.flush();

    FileInputStream inputStream = new FileInputStream(uploadFile);
    byte[] buffer = new byte[4096];
    int bytesRead = -1;
    while ((bytesRead = inputStream.read(buffer)) != -1) {
        outputStream.write(buffer, 0, bytesRead);
    }
    outputStream.flush();
    inputStream.close();

    writer.append(LINE_FEED);
    writer.flush();    
}

public void addHeaderField(String name, String value) {
    writer.append(name + ": " + value).append(LINE_FEED);
    writer.flush();
}

public List<String> finish() throws IOException {
    List<String> response = new ArrayList<String>();

    writer.append(LINE_FEED).flush();
    writer.append("--" + boundary + "--").append(LINE_FEED);
    writer.close();

    // checks server's status code first
    int status = httpConn.getResponseCode();
    if (status == HttpURLConnection.HTTP_OK) {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                httpConn.getInputStream()));
        String line = null;
        while ((line = reader.readLine()) != null) {
            response.add(line);
        }
        reader.close();
        httpConn.disconnect();
    } else {
        throw new IOException("Server returned non-OK status: " + status);
    }

    return response;
}
}

主要代码:

private void TCP_File_Client() throws IOException{
    String url = PATH +"/upload";
    String charset = "UTF-8";
    String param = "value";
    File textFile = new File(data_n3_PATH);
    File binaryFile = new File(data_n3_PATH);
    String boundary = Long.toHexString(System.currentTimeMillis());
    String CRLF = "\r\n";
    URLConnection connection = new URL(url).openConnection();
    HttpURLConnection http = (HttpURLConnection) connection;
    http.setRequestMethod("POST");
    connection.setDoOutput(true);
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);


    File uploadFile1 = new File(data_n3_PATH);
    File uploadFile2 = new File(data_n3_PATH);
    String requestURL = PATH +"/upload";

    try {
        MultipartUtility multipart = new MultipartUtility(requestURL, charset);

        multipart.addHeaderField("User-Agent", "CodeJava");
        multipart.addHeaderField("Test-Header", "Header-Value");

        multipart.addFormField("description", "Cool Pictures");
        multipart.addFormField("keywords", "Java,upload,Spring");

        multipart.addFilePart("fileUpload", uploadFile1);
        multipart.addFilePart("fileUpload", uploadFile2);

        List<String> response = multipart.finish();

        System.out.println("SERVER REPLIED:");

        for (String line : response) {
            System.out.println(line);
        }
    } catch (IOException ex) {
        System.err.println(ex);
    }




}

通过调试我的代码,我发现POST请求可以转到node.js服务器,但我找不到文件。 req.files是空的,我找不到任何看起来像需求的文件。

我收到IOException(&#34;服务器返回非正常状态:&#34; +状态); 500状态

我如何连接这些?

1 个答案:

答案 0 :(得分:0)

阅读https://github.com/expressjs/multer/issues/345。 你可以使用node.js模块multer。