gpt4 book ai didi

java - 正在将图像上传到服务器(服务器上的图像已损坏)

转载 作者:太空宇宙 更新时间:2023-11-04 14:12:54 24 4
gpt4 key购买 nike

我正在尝试使用预先签名的上传 URL 将图像上传到 S3,该 URL 的内容类型设置为 image/jpeg ,方法设置为 PUT。上传后,当我尝试访问 S3 上的图像时,它似乎已损坏,并且大小大于本地镜像文件。我的代码如下。

        URL url = new URL(uploadUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
httpCon.setRequestProperty("Content-Type", "image/jpeg");
OutputStreamWriter out = new OutputStreamWriter(httpCon.getOutputStream());

RandomAccessFile f = new RandomAccessFile(imagePath, "r");
int length = (int) imagePath.length();
byte[] imageData = new byte[length];
f.readFully(imageData);
String data = new String(imageData);
out.write(data);
out.close();

int responseCode = httpCon.getResponseCode();
return (responseCode == HttpStatus.SC_OK);

最佳答案

当您从图像数据创建字符串时,很可能会发生损坏。来自 String 构造函数 String(byte[]) 的 javadoc:

Constructs a new {@code String} by decoding the specified array of bytes using the platform's default charset. The length of the new {@code String} is a function of the charset, and hence may not be equal to the length of the byte array.

修复方法是将字节数组直接写入输出流。

关于java - 正在将图像上传到服务器(服务器上的图像已损坏),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28083106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com