如何使用presignurl从android中的aws S3服务器上传图像

时间:2015-07-25 10:41:28

标签: android amazon-s3 httpurlconnection

我正在尝试将图像从预先签名的URL上传到S3存储桶,它提供了由同行关闭的ssl异常错误连接

这是我的代码

public int upload(String filePath, URL url) {
 Bitmap bm = BitmapFactory.decodeFile(filePath);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.JPEG, 90, bos);
            byte[] fileBytes = bos.toByteArray();

            connection = (HttpURLConnection) url.openConnection();

            connection.setDoOutput(true);
            connection.setRequestMethod("PUT");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type", "application/octet-stream"); 

            OutputStream output = connection.getOutputStream();
            InputStream input = new ByteArrayInputStream(fileBytes);
            byte[] buffer = new byte[4096];
            int length;
            while ((length = input.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            output.flush();

            return connection.getResponseCode();
}

1 个答案:

答案 0 :(得分:2)

最后我弄清楚了, 这是使用预签名URL将图像发送到S3的代码

尝试{

        Bitmap bm = BitmapFactory.decodeFile(fileBytes);
        connection = (HttpsURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/octet-stream"); // Very important ! It won't work without adding this!

        OutputStream output = connection.getOutputStream();


        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 50, output);
        output.flush();

        int response = connection.getResponseCode();

        return connection.getResponseCode();
    } catch (IOException e) {
        e.printStackTrace();
    }