简体   繁体   中英

Java - multipart/form-data POST request using a remote file (with http:// or file:// protocols)

I followed this thread for uploading a multipart/form-data file: how-can-i-make-a-multipart-form-data-post-request-using-java . However I couldn't find anything regarding uploading a file from remote server. for example, lets say i have a file here: file://serverIP/folder/subFolder/file.x I can access the file using http as well: http://serverIP/subFoler/file.x

this is piece my code:

File fileToUpload = new File("file://serverIP/folder/subFolder/file.x");
    HttpPost request = new HttpPost(fullUri);
    HttpEntity multipart = MultipartEntityBuilder.create()
                        .addTextBody("field1", "yes", ContentType.TEXT_PLAIN)
                        .addBinaryBody("file", fileToUpload, ContentType.APPLICATION_OCTET_STREAM, fileToUpload.getName())
                        .build();
    request.setEntity(multipart);

after executibg I get java.io.FileNotFoundException: file:\\serverIP\\folder\\subFolder\\file.x (The filename, directory name, or volume label syntax is incorrect).

Can someone help me understand what is wrong with the path and why the it converts it to file:\\...?

The number of slashes that you put after file: is dependent on the host(in your case remote serverIP's) os environment. For example in windows it generally works file:// but for unix environment it is file:/// . new File(URI) works only on files in local system as only those files are applicable to be accessed using the file: format.

On the other hand idea remains the same and that you need to download the remote file corresponding to the remote url at a tmp local path and then use that tmp file to build the http-request. You can use FileUtils#copyURLToFile

File fileToUpload = new File(_some tmp path_);    
FileUtils.copyURLtoFile(remoteFileUrl, fileToUpload);

Also this does not changes your http-entity since fileToUpload and fileToUpload.getName() still remains the same

PS: be careful while deleting this temp File aka fileToUpload

You can try this...

import java.io.File;
import java.io.IOException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

public class Post_Remote_File {

    private static final String POST_URL = "http://127.0.0.1/post-demo/post-receiver.php";

    public static void main(String[] args) throws IOException {

        File fileToUpload = new File("index.html");
        FileUtils.copyURLToFile(new URL("http://127.0.0.1/post-demo/index.html"), fileToUpload);
        HttpPost request = new HttpPost(POST_URL);
        HttpEntity multipart = MultipartEntityBuilder.create()
                .addTextBody("field1", "yes", ContentType.TEXT_PLAIN)
                .addBinaryBody("file", fileToUpload, ContentType.APPLICATION_OCTET_STREAM, fileToUpload.getName())
                .build();
        request.setEntity(multipart);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = httpClient.execute(request);
        //int code = response.getStatusLine().getStatusCode();
        ResponseHandler<String> handler = new BasicResponseHandler();
        String body = handler.handleResponse(response);
        //HttpEntity responseEntity = response.getEntity();
        System.out.println(body);

    }
}

I am using HttpComponents Core, HttpComponents Client (from Apache HttpComponents ), Commons Logging, Commons IO (from Apache Commons ) and Apache HttpClient Mime . So ensure these are present in classpath before execution (thats why i pasted full code here). Below is the library explorer view for this project, or use Maven to resolve dependencies.

在此处输入图片说明

The problem with this approch : FileUtils will download the file from specified URL, then copy to specified file (you can find index.html on the file explorer of the project) ; this may lead to problems with large file.

很好,答案很愚蠢,但是它对我有用的唯一方法是添加file:/// / (四个反斜杠),并将URI转换为\\\\ serverIP \\ folder \\ subFolder \\ file.x

First things first: On what kind of server are you trying to access the files? Because:

The prefix concept is used to handle root directories on UNIX platforms, and drive specifiers, root directories and UNC pathnames on Microsoft Windows platforms (From Oracle Java docs)

a bit differently. For the hints you can take a look there . Next thing this line:

File fileToUpload = new File("file://serverIP/folder/subFolder/file.x");

if it is a linux server, then this should be sufficient to access the file:

File fileToUpload = new File("serverIP:/here_comes_your_absolute_path");

For "windows" server it should be something looking like the following:

File fileToUpload = new File("\\\\serverIP\\here\\comes\\yourpath\\file.txt")

PS my answer might be incomplete I will be glad to edit it anytime.

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