0

how to send file with http request in java ? i see question Send image file using java HTTP POST connections and Upload files from Java client to a HTTP server but them are too old question and not work any more .

Community
  • 1
  • 1

1 Answers1

3

A good example is given in Multi part File Upload example of Apache HttpClient

http://svn.apache.org/viewvc/httpcomponents/oac.hc3x/trunk/src/examples/MultipartFileUploadApp.java?view=markup

The part that actually posts the file is

            String targetURL = cmbURL.getSelectedItem().toString();
            // add the URL to the combo model if it's not already there
            if (!targetURL
                .equals(
                    cmbURLModel.getElementAt(
                        cmbURL.getSelectedIndex()))) {
                cmbURLModel.addElement(targetURL);
            }

            PostMethod filePost = new PostMethod(targetURL);

            filePost.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE,
            cbxExpectHeader.isSelected());
            try {
                appendMessage("Uploading " + targetFile.getName() + " to " + targetURL);
                Part[] parts = {
                    new FilePart(targetFile.getName(), targetFile)
                };
                filePost.setRequestEntity(
                    new MultipartRequestEntity(parts, filePost.getParams())
                    );
                HttpClient client = new HttpClient();
                client.getHttpConnectionManager().
                    getParams().setConnectionTimeout(5000);
                int status = client.executeMethod(filePost);
                if (status == HttpStatus.SC_OK) {
                    appendMessage(
                        "Upload complete, response=" + filePost.getResponseBodyAsString()
                    );
                } else {
                    appendMessage(
                        "Upload failed, response=" + HttpStatus.getStatusText(status)
                    );
                }
            } catch (Exception ex) {
                appendMessage("ERROR: " + ex.getClass().getName() + " "+ ex.getMessage());
                ex.printStackTrace();
            } finally {
                filePost.releaseConnection();
            }

Hope it is of some help to you.

  • i write my program in console . this not work for me . please simple this if you can – mohammad amin Sep 18 '15 at 20:07
  • i need simple method that give URL and File and send request – mohammad amin Sep 18 '15 at 20:10
  • if you are familiar with github I have uploaded a sample project to post files. This project uses httpclient 4.3.6 so the code is slightly diffrent from the above code.[HttpPostExample](https://github.com/thomasramapuram/httpPostTest) – Thomas Ramapuram Sep 25 '15 at 10:25