数据库中有张表专门存文件的信息,字段包括如:文件名,文件类型,文件路径等等。
下面演示怎么把后台的文件信息返回到前端预览。
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
@RestController
@RequestMapping("/test")
public class TestController {
private static final Logger logger = LoggerFactory.getLogger(TestController.class);
/**
* 文件预览,需注意有些文件(比如word文档)是无法在浏览器预览的,这里演示图片的预览
* @param id
* @param response
*/
@RequestMapping(value = "/view/{id}", method = RequestMethod.GET)
public void view(@PathVariable("id") Long id, HttpServletResponse response) {
/**
* 关于文件的信息,实际中应该是根据某个字段去数据库查询得到的,比如根据该文件记录在DB中的id
* 这里方便演示,我直接写死了文件的路径filePath
*/
String filePath = "E://data/com/test.png"; // 本该根据ID去数据库查,这里是hard code
// 设返回的contentType
response.setContentType("image/png"); // 不同文件的MimeType参考后续链接
// 读取路径下面的文件
try {
FileCopyUtils.copy(new FileInputStream(filePath), response.getOutputStream());
} catch (IOException e) {
logger.error("View document exception, document id is [{}]", id, e);
}
}
}
这样启动项目,在浏览器输入地址就能看到效果。比如:http://localhost:8080/test/view/1
前后端分离时,前台的img标签中,src用访问的URL填充即可。
<img src="http://localhost:8080/test/view/1"/>
更多文件的MimeType参考: