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

标签 java android

我正在尝试使用预先签名的上传 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/

相关文章:

javascript - Java - 在 Eclipse 动态 Web 项目中将 javascript 连接到 servlet

java - boolean 错误(代表我)

java - 哈希表键值对比较以找出唯一的对

Android Phonegap 版本 2.0 或更高版本 facebook、twitter、消息等共享插件的任何更新

Domino/XPage 中字段的 Java 警告

java - MVC 中有多少 GUI 逻辑太多了?

android - Dagger 柄 : Difference between annotating a class @Singleton and a provides function @Singleton

android - FireBase 身份验证登录/注册异常

java - onLocationChanged() 不会自动调用

android - 错误 : "Only the Kotlin standard library is allowed to use the ' kotlin' package"