在Spring MVC Web应用程序中从Amazon S3服务下载上载的文件

时间:2015-04-10 08:53:57

标签: spring spring-mvc amazon-web-services amazon-s3

我遇到从亚马逊s3服务下载我上传的文件的问题。我已经成功实现了上传部分,我只需要将这些文件下载到我的本地硬盘中,以后再查看它们。我的应用程序是一个spring mvc应用程序。

这是我的控制器来调用下载服务

@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());
 }
}

//这是我的S3Sservice类,带有下载方法

 @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());
}


 }

1 个答案:

答案 0 :(得分:2)

哇..解决方案非常简单..我只是使用了html下载链接并在我的jsp上传递了这样的参数。这是我的document.jsp

<a class="btn btn-primary" href="${document.asset.name}" download="${document.asset.name}">Download Document</a>

我在控制器中更改了downloadDocument(),看起来像这样

public void downloadDocument(@RequestParam("docId") Long docId
,HttpServletRequest request ,HttpServletResponse response)){
Document doc = docRepo.findOne(docId);
model.addAtribute("document" , doc);
return "document";
 }
}