我有从Amazon s3服务下载我上传的文件的问题。我已经成功实现了上载部分,我所需要做的就是将这些文件下载到本地hardrive中,以便以后查看。我的应用程序是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());
}
}
哇..解决方案非常简单..我只是使用了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";
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句