title: Downloading uploaded files from Amazon S3 service in a Spring MVC web app
body: <p>I have a problem of downloading my uploaded files from amazon s3 service. I have succesfully implemented the upload section, all I need is to download these file to my local hardrive the view them later. My application is a spring mvc application. </p>
  
  <p>This is my controller to call the download service</p>
  
  <pre><code>@Controller
  public class fileController{
  @Autowired S3Service s3Service;
  @Autowired AwsConfig awsConfig;
  @Autowired Environment env;
  @Autowired DocRepository docRepo;
  
  @RequestMapping(value="downloadDocume")
  public void downloadDocument(@RequestParam("docId") Long docId
  ,HttpServletRequest request ,HttpServletResponse response)){
  Document doc = docRepo.findOne(docId);
  String docName = doc.getAsset().getName();
   String ASSET_PATH = awsConfig.getBaseUrl()+"/"+
                     awsConfig.getBucket()+"/";
  
      if (Objects.equals(env.getProperty("spring.profiles.active"),"prod")){
          ASSET_PATH= awsConfig.getBaseUrl()+"/"+
                  awsConfig.getBucket()+"/";
      }
  
     String filtered = StringUtils.delete(docName, ASSET_PATH);
  String mimetype = request.getSession().getServletContext().getMimeType(filtered);
      FileStream file = s3Service.getAssetByName("/Documents/", filtered);
      response.setContentType(mimetype);
      response.setContentLength((int) file.getSize());
  
      response.setHeader("Content-Disposition","attachment; filename=\"" + docName +"\"");
      FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());
   }
  }
  </code></pre>
  
  <p>//This is my S3Sservice class with the download method</p>
  
  <pre><code> @Service
  public class S3Service{
  public FileStream getAssetByName(String path , String name)
          throws FileNotFoundException{
      AmazonS3Client s3 = new AmazonS3Client(
              new BasicAWSCredentials(awsConfig.getAccessKey(), awsConfig.getSecretKey()));
      s3.setEndpoint(awsConfig.getBaseUrl());
      s3.setS3ClientOptions(new S3ClientOptions().withPathStyleAccess(true));
      S3Object obj = s3.getObject(new GetObjectRequest(awsConfig.getBucket(), getS3Path(path) + name));
      return new FileStream(obj.getObjectContent(), obj.getObjectMetadata().getContentLength());
  }
  
  
   }
  </code></pre>