原作者地址:http://mayday85.iteye.com/blog/1622445
作者解决了我的困惑,表示感谢。
首先说下我的问题:最近做了一个内部使用的AppStore,为了方便前段调用,直接将资源文件放在项目内部(简直太傻逼了),直接导致每次更新项目重新部署就要将之前备份的文件拷入项目内部。随着网站使用文件越来越多,拷文件简直雪崩。
1.如何下载外部文件
通常我们将文件放在项目的webContent下直接拿文件路径就可以访问,如果文件不断添加,就造成很多问题。
还有就是通过jsp下载,读取外部文件,拿到文件流写入本地。
由于我用的ng+h5做前端,现在我需要排除第二种方案。那么如何做下载尼?
package com.baosight.webapp.web;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
*
* @author Venbill
* @TIME 2016-9-27下午04:14:45
* @Description 文件下载测试
*/
@Controller
@RequestMapping("/test")
public class TestController {
// 供ftp上传文件使用
@ResponseBody
@RequestMapping("download")
public ResponseEntity<byte[]> download() throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", "dict.jpg");
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File("d:test/10.jpg")),
headers, HttpStatus.CREATED);
}
}
打开浏览器,下载路径:http://localhost:8888/AppStore/test/download
2如果前端需要引用这个文件,现在这个文件不能直接引用怎么办?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>读取项目外的图片,放入html展示</h1>
<img alt="" src="http://localhost:8888/AppStore/test/download">
</body>
</html>
打开页面,完美引用