开发者

Image writing over URLConnection

I am trying to write an image over an HttpURLConnection.

I know how to write text but I am having real problems trying to write an image

I have succeeded in writing to the local HD using ImageIO:

But I am trying to write Image by ImageIO on url and failed

URL url = new URL(uploadURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setUseCaches(false);
connection.setRequestProperty("Content-Type", "multipart/form-data;
                                            boundary=" + boundary);
output = new DataOutputStream(connection.getOutputStream());
output.writeBytes("--" + boundary + "\r\n");
output.writeBytes("Content-Disposition: form-data; name=\"" + FIELD_NAME + "\";
                                            filename=\"" + fileName + "\"\r\n");
output.writeBytes("Content-Type: " + dataMimeType + "\r\n");
output.writeBytes("Content-Transfer-Encoding: binary\r\n\r\n");
ImageIO.write(image, imageType, output);

the uploadURL i开发者_如何转开发s the url to an asp page on the server which will upload the image with the file name given in "content-Disposition: part.

now when I send this then asp page find the request and find the name of file. but does not find the file to be uploaded.

The problem is that when writing by ImageIO on URL what will the name of the file on which the ImageIO is writing,

So please help me how ImageIO will write an image on URLConnection and how can I know the name of the file which I have to use in the asp page to upload the file

Thanks for taking the time to read this post Dilip Agarwal


First I believe that you should call io.flush() and then io.close() after writing image.

Second content type seems strange for me. It seems that you are trying to submit form while it is actually image. I do not know what does your asp expect but typically when I write code that should transfer file over HTTP I send appropriate content type, e.g. image/jpeg.

Here is for example code snippet I extracted from one small utility that I wrote and I am using during my current work:

    URL url = new URL("http://localhost:8080/handler");
    HttpURLConnection con = (HttpURLConnection)url.openConnection();
    con.setDoInput(true);
    con.setDoOutput(true);
    con.setUseCaches(false);
    con.setRequestProperty("Content-Type", "image/jpeg");
    con.setRequestMethod("POST");
    InputStream in = new FileInputStream("c:/temp/poc/img/mytest2.jpg");
    OutputStream out = con.getOutputStream();
    copy(in, con.getOutputStream());
    out.flush();
    out.close();
    BufferedReader r = new BufferedReader(new  InputStreamReader(con.getInputStream()));


            // obviously it is not required to print the response. But you have
            // to call con.getInputStream(). The connection is really established only
            // when getInputStream() is called.
    System.out.println("Output:");
    for (String line = r.readLine(); line != null;  line = r.readLine()) {
        System.out.println(line);
    }

I used here method copy() that I took from Jakarta IO utils. Here is the code for reference:

protected static long copy(InputStream input, OutputStream output)
        throws IOException {
    byte[] buffer = new byte[12288]; // 12K
    long count = 0L;
    int n = 0;
    while (-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
        count += n;
    }
    return count;
}

Obviously the server side must be ready to read the image content directly from POST body. I hope this helps.


The OP seems lost into oblivion but for the benefit of Mister Kite :

// main method 
URL url = new URL(uploadURL);
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true); // triggers "POST"
// connection.setDoInput(true); // only if needed
connection.setUseCaches(false); // dunno
final String boundary = Long.toHexString(System.currentTimeMillis());
connection.setRequestProperty("Content-Type", "multipart/form-data; boundary="
                                                                + boundary);
output = new DataOutputStream(connection.getOutputStream());
try {
     // image must be a File instance
    flushMultiPartData(image, output, boundary);
} catch (IOException e) {
    System.out.println("IOException in flushMultiPartData : " + e);
    return;
}
// ...
private void flushMultiPartData(File file, OutputStream serverOutputStream,
            String boundary) throws FileNotFoundException, IOException {
    // SEE https://stackoverflow.com/a/2793153/281545
    PrintWriter writer = null;
    try {
        // true = autoFlush, important!
        writer = new PrintWriter(new OutputStreamWriter(serverOutputStream,
                charsetForMultipartHeaders), true);
        appendBinary(file, boundary, writer, serverOutputStream);
        // End of multipart/form-data.
        writer.append("--" + boundary + "--").append(CRLF);
    } finally {
        if (writer != null) writer.close();
    }
}

private void appendBinary(File file, String boundary, PrintWriter writer,
        OutputStream output) throws FileNotFoundException, IOException {
    // Send binary file.
    writer.append("--" + boundary).append(CRLF);
    writer.append(
        "Content-Disposition: form-data; name=\"binaryFile\"; filename=\""
            + file.getName() + "\"").append(CRLF);
    writer.append("Content-Type: "
            +  URLConnection.guessContentTypeFromName(file.getName()))
            .append(CRLF);
    writer.append("Content-Transfer-Encoding: binary").append(CRLF);
    writer.append(CRLF).flush();
    InputStream input = null;
    try {
        input = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        for (int length = 0; (length = input.read(buffer)) > 0;) {
            output.write(buffer, 0, length);
        }
        output.flush(); // Important! Output cannot be closed. Close of
        // writer will close output as well.
    } finally {
        if (input != null) try {
            input.close();
        } catch (IOException logOrIgnore) {}
    }
    writer.append(CRLF).flush(); // CRLF is important! It indicates end of
    // binary boundary.
}

You may want to add Gzip compression - see file corrupted when I post it to the servlet using GZIPOutputStream for a working class with or without Gzip. The ImageIO has no place here - just write the bytes past the wire and use ImageIO to your heart's content on the server. Based on @BalusC answer

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜