how to upload file to http remote server using java? [duplicate]

与世无争的帅哥 提交于 2019-11-29 04:25:23

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

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

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); 

You can use httpclient.

Send the the files using POST as a method.

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

Raslan

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!