用Java分段上传图像

时间:2014-01-23 05:01:58

标签: java httpurlconnection multipartform-data multipart

我正在尝试通过Java代码将文件附加到http://example.com:8080/attachments。我正在使用多部分数据上传。我尝试上传文本文件,并且工作正常。当我尝试jpg文件时,响应代码为200,但上传的文件存在一些问题。它说文件已损坏。

将图像转换为字节数组的代码。

             byte[] bFile = new byte[(int) file.length()];
             fileInputStream = new FileInputStream(file);
             int bytesAvailable = fileInputStream.available();
             int maxBufferSize = 4096;

             byte[] buffer = new byte[bytesAvailable];
             ByteArrayOutputStream bos = new ByteArrayOutputStream();

             int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

             while (bytesRead > 0) {
                bos.write(buffer, 0, bytesAvailable);
                 bytesAvailable = fileInputStream.available();
                 bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
                 bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
             }
             bFile = bos.toByteArray();

上传代码

        String contentDisposition = "Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"";
        String contentType = "Content-Type: image/jpg";         
        String BOUNDARY = "*****";
        HttpsURLConnection connection;
        String CRLF = "\r\n";   
        StringBuffer requestBody = new StringBuffer();
        requestBody.append("--");
        requestBody.append(BOUNDARY);
        requestBody.append(CRLF);
        requestBody.append(contentDisposition);
        requestBody.append(CRLF);
        requestBody.append(contentType);
        requestBody.append(CRLF);
        requestBody.append(CRLF);
        requestBody.append(new String(bFile));
        requestBody.append(CRLF);
        requestBody.append("--");
        requestBody.append(BOUNDARY);
        requestBody.append("--");

        URL obj = new URL("url");
        connection = (HttpsURLConnection) obj.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
        connection.setRequestProperty("User-Agent", "Mozilla/5.0");
        connection.setRequestProperty("Accept","*/*");
        connection.setRequestProperty("Authorization", strEncoded);
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);

        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setUseCaches(false);
        DataOutputStream wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(requestBody.toString());
        wr.flush();
        wr.close();

如果我为图片发送的字节数组有任何问题,请告诉我。

请检查附加的屏幕截图以获取错误消息。

http://tinypic.com/r/33233hl/5

感谢。

1 个答案:

答案 0 :(得分:0)

您读取文件字节的代码容易出错,请查看this question的答案。

您不能只在请求体中添加字节
requestBody.append(new String(bFile));
这会将图像字节转换为你想要的字符 - 你需要从图像文件中读取字节时传输的字节。

不要手动执行此操作,而是使用Apache HttpClient之类的东西。它可以处理将文件字节正确放入http-post中的细节。查看官方example或查看this question中的代码。