一、上传轮播(包含图片文件)
/**
* 添加轮播信息
*
* @param request
* @param file
* @param carousel
* @return
* @throws IOException
*/
@RequestMapping(value = "/addCarousel")
public RecycleResult addCarousel(HttpServletRequest request, MultipartFile file, Carousel carousel) throws IOException {
if (file == null || StringUtils.isBlank(file.getOriginalFilename())){
RecycleResult.build(500, "文件不能为空");
}
String rootPath = ResourceUtils.getURL("").getPath() + "static/upload/";
File rootFile = new File(rootPath);
if (!rootFile.exists()) {
rootFile.mkdirs();
}
String realPath = new Date().getTime() + file.getOriginalFilename();
//存储文件
File storeFile = new File(rootPath + realPath);
file.transferTo(storeFile);
//写入数据库
carousel.setPhotoPath(realPath);
if (carousel != null){
cmsService.addCarousel(carousel);
}
return RecycleResult.ok();
}
二、nginx代理(存储到本地磁盘)
server {
listen 8018;
server_name localhost;
location / {
root D:/development/project/green/green-collection/static/upload/;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
重启: ./nginx -s reload
三、访问本地资源(根据id访问轮播详情)
(1)获取URL参数 id
$(function() {
//获取参数id
var a = GetRequest();
var id = a['id'];
//获取轮播图详细信息
viewCarouselDetailById(id);
});
//获取页面传递参数
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if(url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for(var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = decodeURIComponent(strs[i].split("=")[1]);
}
}
return theRequest;
}
(2)根据id获取相应信息
//查看轮播图详细信息
function viewCarouselDetailById(id) {
$.get("http://192.168.1.119:9911/cms/viewCarouselDetail/" + id,
function(data, status) {
//时间格式化
data.createTime = timestampToTime(data.createTime);
new Vue({
el: '#app', //元素
data: {
info: data
}
})
}
)
}
//时间格式化
function timestampToTime(timestamp) {
var date = new Date(timestamp);//时间戳为10位需*1000,时间戳为13位的话不需乘1000
Y = date.getFullYear() + '-';
M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
D = date.getDate() + ' ';
h = date.getHours() + ':';
m = date.getMinutes() + ':';
s = date.getSeconds();
return Y+M+D+h+m+s;
}
(3)结合vue.js渲染数据
<div id="app">
<!--<h1 class="z_title">{{info.title}}</h1>-->
<div class="z_photoPath">
<img v-bind:src="['http://192.168.1.119:8018/'+info.photoPath]" />
</div>
<p class="z_info">
<span class="z_posterName">作者:{{info.posterName}}</span>
<span class="z_createTime">发布时间:{{info.createTime}}</span>
</p>
<p class="z_content"> {{info.description}}</p>
</div>
本文介绍了:上传文件,将文件存储到本地,访问本地文件,渲染数据的整个流程。