How to post image data from java

Hey, I tried exploring how POST data is from java and it doesn't do anything like what I want to do. Basically, this is a form for uploading an image to a server, and I want to publish the image on the same server, but from java. It must also have a valid parameter name (regardless of the form input name). I would also like to return a response from this method.

It puzzles me why it is so hard to find, because it seems to be something so basic.

EDIT ---- Added code

Based on some of the things that BalusC showed, I created the following method. It still does not work, but its the most successful thing that I have received yet (it seems that it sends something to another server and returns some kind of answer - I'm not sure I got the answer correctly):

EDIT2 ---- added to BalusC feedback based code

EDIT3 ---- publishing code that works pretty much , but seems to have a problem :

 ....

 FileItemFactory factory = new DiskFileItemFactory();

 // Create a new file upload handler
 ServletFileUpload upload = new ServletFileUpload(factory);

 // Parse the request
 List<FileItem> items = upload.parseRequest(req);

 // Process the uploaded items
 for(FileItem item : items) {
     if( ! item.isFormField()) {
         String fieldName = item.getFieldName();
         String fileName = item.getName();
         String itemContentType = item.getContentType();
         boolean isInMemory = item.isInMemory();
         long sizeInBytes = item.getSize();

         // POST the file to the cdn uploader
         postDataRequestToUrl("<the host im uploading too>", "uploadedfile", fileName, item.get());

     } else {
         throw new RuntimeException("Not expecting any form fields");
     }
 }

....

// Post a request to specified URL. Get response as a string.
public static void postDataRequestToUrl(String url, String paramName, String fileName, byte[] requestFileData) throws IOException {
 URLConnection connection=null;

 try{
     String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value.
     String charset = "utf-8";

     connection = new URL(url).openConnection();
     connection.setDoOutput(true);
     connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
     PrintWriter writer = null;
     OutputStream output = null;
     try {
         output = connection.getOutputStream();
         writer = new PrintWriter(new OutputStreamWriter(output, charset), true); // true = autoFlush, important!

         // Send binary file.
         writer.println("--" + boundary);
         writer.println("Content-Disposition: form-data; name=\""+paramName+"\"; filename=\"" + fileName + "\"");
         writer.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileName));
         writer.println("Content-Transfer-Encoding: binary");
         writer.println();

         output.write(requestFileData, 0, requestFileData.length);
         output.flush(); // Important! Output cannot be closed. Close of writer will close output as well.

         writer.println(); // Important! Indicates end of binary boundary.

         // End of multipart/form-data.
         writer.println("--" + boundary + "--");
     } finally {
         if (writer != null) writer.close();
         if (output != null) output.close();
     }

     //*  screw the response

     int status = ((HttpURLConnection) connection).getResponseCode();
     logger.info("Status: "+status);
     for (Map.Entry<String, List<String>> header : connection.getHeaderFields().entrySet()) {
         logger.info(header.getKey() + "=" + header.getValue());
     }

 } catch(Throwable e) {
     logger.info("Problem",e);
 } 

}

I see this code loading the file, but only after I turned off tomcat. It makes me think that I am leaving some kind of connection open.

It worked!

+3
source share
2 answers

The main API you want to use is java.net.URLConnection. This, however, is rather low and verbose. You will learn more about the specifics of HTTP and consider them ( headers , etc.). You can find a related question here with a lot of examples .

API- HTTP Apache Commons HttpComponents Client. .


: : , char. . HTTP- Gathering . :

BufferedReader reader = null;
StringBuilder builder = new StringBuilder();

try {
    reader = new BufferedReader(new InputStreamReader(response, charset));
    for (String line; (line = reader.readLine()) != null;) {
        builder.append(line);
    }
} finally {
    if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}

return builder.toString();

2: . , / , , Java IO:) , . Apache Commons FileUpload multipart/form-data . / . " ". , , ( ).


3:

, , , tomcat. , - .

OutputStream, . Java IO.


+4

? Google Http Post Java, - ? , http://www.devx.com/Java/Article/17679/1954 .

+1

Source: https://habr.com/ru/post/1758437/


All Articles