简体   繁体   中英

Unable to send multipart post, using java, to node.js API server

I've got a Node.js API that uses multer to handle multipart POST requests.

I am able to create a simple HTML form and POST images from there successfully.

I can also use postman to get the request to go through, but the req.file is always undefined on the server when I try to use my java method (below).

Called Method

public static void testPostImage() throws Exception {
    String charset = "UTF-8";

    String requestURL = "http://localhost:3000/accounts/2/details";

    try {
        File outputfile = new File(Util.getWorkingDirectory() + "/details");

        MultipartUtility multipart = new MultipartUtility(requestURL, charset);
        multipart.addFilePart("details", new File(outputfile.getAbsolutePath()));

        List<String> response = multipart.finish();
        General.println("SERVER REPLIED:");
        for (String line : response) {
            General.println(line);
        }
    } catch (IOException ex) {
        General.println(ex);
    }
}

The MultipartUtility class comes from this tutorial .

The contents of the constructor and 'addFilePart'...

Constructor

public MultipartUtility(String requestURL, String charset)
        throws IOException {
    this.charset = charset;

    // creates a unique boundary based on time stamp
    boundary = "===" + System.currentTimeMillis() + "===";

    URL url = new URL(requestURL);
    httpConn = (HttpURLConnection) url.openConnection();
    httpConn.setUseCaches(false);
    httpConn.setDoOutput(true); // indicates POST method
    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);
}

addFilePart

private static final String LINE_FEED = "\r\n";

public void addFilePart(String fieldName, File uploadFile)
        throws IOException {

    General.println("Sending to " + fieldName + ": " + uploadFile.getAbsolutePath());

    // Add boundary
    writer.append("--" + boundary).append(LINE_FEED);

    // Add form data
    writer.append("Content-Disposition: form-data;"
            + "name=\"myFile\";"
            + "filename=\"" + fieldName + "\""
            + "\nContent-Type: text/plain\n\n").append(LINE_FEED);

    writer.append("Content-Type: " + "multipart/form-data").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();
}

Their might be more to it but you don't have the right line ending between your Content-disposition and Content-type header:

// Add form data
writer.append("Content-Disposition: form-data;"
        + "name=\"myFile\";"
        + "filename=\"" + fieldName + "\"").append(LINE_FEED);

 writer.append("Content-Type: text/plain").append(LINE_FEED).append(LINE_FEED); // need 2 line feeds

Also you are mixing the order/type of headers

writer.append("Content-Type: " + "multipart/form-data").append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);

Should come before your encoded data.

See examples here

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