Java中图像的多部分上传
我正试图通过Java代码将文件附加到。我使用多部分数据上传。我试过上传文本文件,效果很好。当我尝试jpg文件时,响应代码是200,但是上传的文件有一些问题。它说文件已损坏 用于将图像转换为字节数组的代码Java中图像的多部分上传,java,httpurlconnection,multipartform-data,multipart,Java,Httpurlconnection,Multipartform Data,Multipart,我正试图通过Java代码将文件附加到。我使用多部分数据上传。我试过上传文本文件,效果很好。当我尝试jpg文件时,响应代码是200,但是上传的文件有一些问题。它说文件已损坏 用于将图像转换为字节数组的代码 byte[] bFile = new byte[(int) file.length()]; fileInputStream = new FileInputStream(file); int bytesAvailable
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();
请让我知道我发送的图像字节数组是否有任何问题
请检查所附的屏幕截图以获取错误消息
谢谢。您读取文件字节的代码很容易出错,请查看您的答案 您不能只在请求正文中添加字节
requestBody.append(新字符串(bFile))代码>
这会将图像字节转换为您不想要的字符-您需要在从图像文件读取它们时传输字节
使用ApacheHttpClient之类的工具,而不是手动执行此操作。它可以处理一些细节,比如在http post中正确放置文件字节。见官方或查看中的代码。谢谢@vanOekal。问题在于发送字节。我将代码替换为while(bytesRead>0){write(buffer,0,bytesavable);bytesavable=fileInputStream.available();bytesavable=Math.min(bytesavable,maxBufferSize);bytesRead=fileInputStream.read(buffer,0,bytesavable);}
现在可以正常工作了。