2017-05-25 110 views
0

我正在使用以下代碼從AWS S3存儲桶下載圖像。從S3 Bucket下載圖像後,未從內容中獲取圖像內容

com.amazonaws.services.s3.model.S3Object object = s3Client.getObject(new 
GetObjectRequest(bucketName, mediaItem.getFileName())); 
    S3ObjectInputStream objectData = object.getObjectContent(); 
    object.close(); 
    return objectData.toString(); 

我得到200響應,但在imageview中它說不是圖像。

+0

其實我想知道如何從S3ObjectInputStream中設置javax.servlet.ServletOutputStream,同時從S3獲取圖像。請幫忙。 – vijay

回答

0

下面是從AWS S3存儲桶獲取對象並將對象流寫入servlet響應的代碼。我將內容配置用作「內聯」,因此它直接在瀏覽器上顯示對象。它不會彈出「另存爲」。您可以根據您的要求將其更改爲不同的內容處置方式。

Content disposition

我已經使用了訪問密鑰和祕密密鑰來獲得客戶S3。如果您從可訪問S3存儲桶的EC2運行應用程序,則可將其更改爲InstanceProfileCredentialsProvider(即註釋代碼)。

public class GetS3Object extends HttpServlet { 

    private static final long serialVersionUID = -3924600769478978726L; 

    private static Logger logger = Logger.getLogger(GetS3Object.class); 

    @Override 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     this.doGet(req, resp); 
    } 

    @Override 
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 

     ServletOutputStream out = resp.getOutputStream(); 

     /*AmazonS3 s3Client = AmazonS3ClientBuilder.standard() 
       .withCredentials(new InstanceProfileCredentialsProvider(false)).build();*/ 

     BasicAWSCredentials awsCreds = new BasicAWSCredentials("accesskey", "secretkey"); 
     AmazonS3 s3Client = AmazonS3ClientBuilder.standard() 
           .withCredentials(new AWSStaticCredentialsProvider(awsCreds)) 
           .build(); 

     try { 

      GetObjectRequest getObjectRequest = new GetObjectRequest("yourbucketName", "objectkey"); 
      S3Object s3Object = s3Client.getObject(getObjectRequest); 

      byte[] s3Content = org.apache.commons.io.IOUtils.toByteArray(s3Object.getObjectContent()); 

      resp.setHeader("Content-Type", 
        getServletContext().getMimeType(s3Object.getObjectMetadata().getContentType())); 
      resp.setHeader("Content-Length", String.valueOf(s3Content.length)); 
      resp.setHeader("Content-Disposition", "inline; filename=\"" + "Google_logo.jpeg" + "\""); 

      out.write(s3Content); 

     } catch (Exception e) { 
      e.printStackTrace(); 

     } finally { 
      if (out != null) { 
       out.flush(); 
       out.close(); 
      } 
     } 

    } 

} 
+0

感謝它的工作 – vijay

+0

如果有幫助,您能接受答案嗎?謝謝! – notionquest