how to upload file to http remote server using jav

2019-01-24 11:25发布

问题:

This question already has an answer here:

  • How to use java.net.URLConnection to fire and handle HTTP requests 11 answers

I need to upload images and txt files from my application to a remote server (Just http no ftp) using java. My application is in jsf framework. I searched but no suitable things found. Can anybody guide me? In fact I should upload files to special folder to remote server. I have two application with shared path to upload files, so for accessing them to this files, I decidec to upload shared files(such as images and texts) to third server. First application should upload files to this remote server and second application should read them from it. So my hard part of this solution is to upload files to this third server(in fact remote server) using http.

回答1:

To upload file to a specific folder, your server API must support that.

Server side for receiving uploaded files, you can use http://commons.apache.org/fileupload/

Client side for sending a file upload request, you can use https://hc.apache.org/httpcomponents-client-ga/index.html



回答2:

Have a look at apache commons-fileupload. You can find sample code here.



回答3:

Use following code:

        byte[] data = bos.toByteArray();//convert ur file into byte[]
        HttpClient httpClient = new DefaultHttpClient();//Client
        HttpPost postRequest = new HttpPost(YOUR_SERVER_URL);//Post Request to specified URL
        ByteArrayBody bab = new ByteArrayBody(data, "a.txt");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);// Multipart data
        reqEntity.addPart("uploadingFile", bab); //adding data to request entity
        postRequest.setEntity(reqEntity);//adding request entity to post request
        HttpResponse response = httpClient.execute(postRequest); 


回答4:

You can use httpclient.

Send the the files using POST as a method.



回答5:

As per your requirement, you need to send multiple images & text files,So HTTP multi part file upload seems to be a suitable solution.You can get further information on this from here: http://commons.apache.org/fileupload/using.html



回答6:

make

@Autowired
ServletContext c;

or take object

byte[] bytes = file.getBytes();

String UPLOAD_FOLDEdR=c.getRealPath("/images");  
Path path = Paths.get(UPLOAD_FOLDEdR +"/"+ file.getOriginalFilename());
Files.write(path, bytes);
System.out.println(path);
String Pic_Name =file.getOriginalFilename();