how to upload file to http remote server using jav

2019-01-24 11:48发布

This question already has an answer here:

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.

6条回答
爷、活的狠高调
2楼-- · 2019-01-24 11:50

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

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-24 11:50

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); 
查看更多
Explosion°爆炸
4楼-- · 2019-01-24 11:56

You can use httpclient.

Send the the files using POST as a method.

查看更多
孤傲高冷的网名
5楼-- · 2019-01-24 11:56

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();
查看更多
Animai°情兽
6楼-- · 2019-01-24 12:04

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

查看更多
Luminary・发光体
7楼-- · 2019-01-24 12:13

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

查看更多
登录 后发表回答