问题:
我的apk文件不能完全从任何人的Android浏览器下载,但可以在PC的浏览器下成功下载。实际上,我的apk文件有5.9 MB,但它总共只能下载1.2KB。因此,我得到了“分析失败”错误。
Web服务器: linux + tomcat 7.x + jdk1.7,它在tomcat服务器web.xml中设置了apk mime类型。
网络应用:春季4.0.2 +春季mvc + mybatis,
测试链接: http://127.0.0.1:8080/testapk/appstore/download
下载功能:
@RequestMapping(value = "/appstore/download", method = RequestMethod.GET)
public ResponseEntity<byte[]> download() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
//Linux env.
File file = new File("/usr/appstore/test.apk");
if (!file.exists()) {
//test env. windows
file = new File("D:/test.apk");
if(!file.exists()){
throw new FileNotFoundException("Oops! can not find app file.");
}
}
String fileName = FilenameUtils.getName(file.getAbsolutePath());
//
fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName);
//
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}
答案 0 :(得分:1)
我按照Bradford200的建议解决了这个问题。我认为原因是我没有添加produces="application/apk
的注释,或者原因是我没有添加其他标题,我的新代码在下面:
@RequestMapping(value = "/appstore/download", method = RequestMethod.GET, produces="application/apk")
public ResponseEntity<InputStreamResource> download() throws IOException {
File file = new File("/usr/appstore/test.apk");
if (!file.exists()) {
file = new File("D:/test.apk");
if(!file.exists()) {
throw new FileNotFoundException("Oops! File not found");
}
}
InputStreamResource isResource = new InputStreamResource(new FileInputStream(file));
FileSystemResource fileSystemResource = new FileSystemResource(file);
String fileName = FilenameUtils.getName(file.getAbsolutePath());
fileName=new String(fileName.getBytes("UTF-8"),"iso-8859-1");
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Pragma", "no-cache");
headers.add("Expires", "0");
headers.setContentLength(fileSystemResource.contentLength());
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<InputStreamResource>(isResource, headers, HttpStatus.OK);
}