1.运行环境
myeclipse+mysql+jdk1.7
Sping、SpingMVC、Mybatis三大框架的必要jar包。
当然必要的还有文件上传的jar包
讲下小编最近在做的一个实训项目:MC音乐在线网站,因为本人主要负责后台的编写,而歌曲少不了文件的上传和下载,但是文件上传在我的分工中有,所以这里我就只写我写的文件上传。其实下载也差不多,后续可能补上!!
就我选中的两个包!!!!!!!!!!!!!!!!!!!!
2、我项目设计的图片的上传(主要分三部分)
2.1由于我的后台上传方法都写好了 主要就是怎么来调用了!!先看我的文件上传下载的服务实现接口!!
package cn.service.impl.admin;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletRequest;
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.Service;
import org.springframework.web.multipart.MultipartFile;
import cn.exception.FileUpSizeOverException;
import cn.exception.FileUpUrlException;
import cn.service.FileService;
import cn.service.admin.AdminFileService;
@Service
public class AdminFileServiceImpl implements AdminFileService{
@Override
public String FileUp(MultipartFile file, String url,HttpServletRequest request)
throws FileUpUrlException, FileUpSizeOverException {
//请求的当前路径
String path = request.getSession().getServletContext().getRealPath(url);
//文件名
String fileName =UUID.randomUUID().toString()+"."+file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileName = url+fileName;
return fileName;
}
@Override
public long FileUp(MultipartFile[] files, String url,HttpServletRequest request)
throws FileUpUrlException, FileUpSizeOverException {
long startTime = System.currentTimeMillis();
String path = request.getSession().getServletContext().getRealPath(url);
for(MultipartFile file :files ){
//文件名称 = uuid+后缀
String fileName = UUID.randomUUID().toString()+"."+
file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);;
//System.out.println(path);
File targetFile = new File(path, fileName);
if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
}catch (Exception e) {
e.printStackTrace();
}
}
long endTime = System.currentTimeMillis();
return endTime-startTime;
}
@Override
public ResponseEntity<byte[]> FileDown(List<String> list,HttpServletRequest request) throws IOException {
File file ;//最后下载路径
String downloadFielName;
if(list.size()>1){
String uuid = UUID.randomUUID().toString();
String tmpFileName = uuid+".zip"; //压缩文件临时名称
//压缩文件存储路径
String strZipPath=request.getSession().getServletContext().getRealPath("/")+"/mc/"+tmpFileName;
//创建压缩文件
File tmpZipFile = new File(strZipPath);
if (!tmpZipFile.exists())
tmpZipFile.createNewFile();
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipPath));
//文件组创建
File[] file1 =new File[list.size()] ;
for(int i=0;i<list.size();i++){
String fileUrl = request.getSession().getServletContext().getRealPath("/")+list.get(i);
//System.out.println(fileUrl);
file1[i]=new File(fileUrl);
}
//存储容器
byte[] buffer = new byte[1024];
for (int i = 0; i < file1.length; i++) {
FileInputStream fis = new FileInputStream(file1[i]);
out.putNextEntry(new ZipEntry(UUID.randomUUID().toString()+file1[i].getName()));
//设置压缩文件内的字符编码,不然会变成乱码
//out.setEncoding("UTF-8");
int len;
// 读入需要下载的文件的内容,打包到zip文件
while ((len = fis.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
out.closeEntry();
fis.close();
}
out.close();
file = new File(request.getSession().getServletContext().getRealPath("/")+"/mc/"+tmpFileName);
//下载显示的文件名,解决中文名称乱码问题
downloadFielName = new String(tmpFileName.getBytes("UTF-8"),"iso-8859-1");
}
else{
file = new File(request.getSession().getServletContext().getRealPath("/")+list.get(0));
//下载显示的文件名,解决中文名称乱码问题
downloadFielName = new String(list.get(0).getBytes("UTF-8"),"iso-8859-1");
}
HttpHeaders headers = new HttpHeaders();
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
}
@Override
public boolean deletUserImg(String url, HttpServletRequest request) throws FileUpUrlException{
String path = request.getSession().getServletContext().getRealPath("");
File file = new File(path,url);
if (file.exists()) {
file.delete();
return true;
}else{
throw new FileUpUrlException("路径错误");
}
}
}
2.2视图传递controller效果:()
package cn.controller.admin;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.exception.AdminException;
import cn.exception.StateBlockException;
import cn.pojo.PageBasePo;
import cn.pojo.SongListPo;
import cn.pojo.SongPo;
import cn.pojo.vo.SongListVo;
import cn.pojo.vo.SongVo;
import cn.service.impl.admin.AdminSongListServiceImpl;
import cn.service.impl.admin.AdminSongServiceImpl;
@Controller
@RequestMapping("/admin")
public class AdminSongListController {
@Autowired
private AdminSongListServiceImpl adminSongListServiceImpl;
//查询所有的歌单Po
@RequestMapping("/getAllSongList")
public String getAllSongList(HttpServletRequest request,Model model,Integer pageIndex){
String songListName=request.getParameter("search");
SongListVo songListVo=new SongListVo();
SongListPo songListPo=new SongListPo();
if(songListName!=null)
{
songListPo.setSonglistname(songListName);
}
songListVo.setSongListPo(songListPo);
PageBasePo<SongListVo> pageBasePo=adminSongListServiceImpl.filter1(songListVo, 5, pageIndex);
//System.out.println(pageBasePo);
model.addAttribute("pageBasePo", pageBasePo);
model.addAttribute("search",songListName);
return "admin/songlist";
}
//删除
@RequestMapping("/deleteSongListPo")
public String deleteSongListPo(int songListId){
//System.out.println(songListId);
try {
adminSongListServiceImpl.deleteSongList(songListId);
} catch (AdminException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "forward:getAllSongList";
}
//修改
@RequestMapping("/updateSongListPoReturn")
public String updateSongListPoReturn(HttpServletRequest request,SongListPo songListPo){
System.out.println(songListPo);
String url=request.getParameter("url");
if(url!=null&&url!=""){
songListPo.setImgurl(url);
}
try {
adminSongListServiceImpl.updateSongList(songListPo);
} catch (AdminException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "forward:getAllSongList";
}
//分页
@RequestMapping("/getPageSongList")
@ResponseBody
public PageBasePo<SongListVo> getPageSongList(String search,Integer pageIndex){
SongListVo songListVo=new SongListVo();
SongListPo songListPo=new SongListPo();
if(search!=null)
{
songListPo.setSonglistname(search);
}
songListVo.setSongListPo(songListPo);
PageBasePo<SongListVo> pageBasePo=adminSongListServiceImpl.filter1(songListVo, 5, pageIndex);
return pageBasePo;
}
}
建议在后台传给前台的JSON对象的时候是分页对象,这样方便在前台取值,也好数据回显。。。
2.3下面来看前台页面<div class="center">
<table border="1px red solid">
<thead>
<tr >
<th width="120px">歌单封面</th>
<th width="100px">歌单名称</th>
<th width="100px">歌单热度</th>
<th width="100px">收藏次数</th>
<th width="100px">标签</th>
<th width="100px">操作</th>
</tr>
</thead>
<tbody class="tb">
<c:forEach items="${pageBasePo.list}" var="songListVo">
<tr>
<td><img src="..${songListVo.songListPo.imgurl}"/></td>
<td>${songListVo.songListPo.songlistname}</td>
<td>${songListVo.songListPo.accesscount}</td>
<td>${songListVo.songListPo.collectioncount}</td>
<td>${songListVo.songListPo.tags}</td>
<td>
<a href="getSongListById?songListId=${songListVo.songListPo.songlistid}"><button class="layui-btn layui-btn-small"><i class="layui-icon"></i></button></a>
<a href="deleteSongListPo?songListId=${songListVo.songListPo.songlistid}"><button class="layui-btn layui-btn-small"><i class="layui-icon"></i></button></td>
</tr>
</c:forEach>
</tbody>
</table>
<div id="ul"></div>
</div>
var pageCount=5*${pageBasePo.pageCount};
laypage.render({
elem: 'ul',
count:pageCount ,
limit:5,
first: '首页',
last: '尾页',
prev: '<em>←</em>',
next: '<em>→</em>',
jump: function(obj, first){//页面跳转执行函数
var search=$("#search").val();
var pageIndex =obj.curr;//当前页码
if(!first){ //首次不执行
$.get(//ajax刷新数据
"getPageSongList",
{search:search,pageIndex:pageIndex},
function(data){
$(".tb").html("");//清空子节点
data.list.forEach(function(value,index){//数据渲染
//控制台输出测试 console.log(value);
var $tr=$('<tr><td><img src="..'+value.songListPo.imgurl+'"/></td>'
+'<td>'+value.songListPo.songlistname+'</td>'
+'<td>'+value.songListPo.accesscount+'</td>'
+'<td>'+value.songListPo.collectioncount+'</td>'
+'<td>'+value.songListPo.tags+'</td>'
+'<td><a href="getSongListById?songListId='+value.songListPo.songlistid+'">
<button class="layui-btn layui-btn-small"><i class="layui-icon"></i><button></a>'
+'<a href="deleteSongListPo?songListId='+value.songListPo.songlistid+'">
<button data-method="confirmTrans" class="layui-btn layui-btn-small"><i class="layui-icon"></i><button></td></tr>');
$(".tb").append($tr);
});
}
);
}
}
});
});
<div class="center">
<table border="1px red solid">
<thead>
<tr >
<th width="120px">歌单封面</th>
<th width="100px">歌单名称</th>
<th width="100px">歌单热度</th>
<th width="100px">收藏次数</th>
<th width="100px">标签</th>
<th width="100px">操作</th>
</tr>
</thead>
<tbody class="tb">
<c:forEach items="${pageBasePo.list}" var="songListVo">
<tr>
<td><img src="..${songListVo.songListPo.imgurl}"/></td>
<td>${songListVo.songListPo.songlistname}</td>
<td>${songListVo.songListPo.accesscount}</td>
<td>${songListVo.songListPo.collectioncount}</td>
<td>${songListVo.songListPo.tags}</td>
<td>
<a href="getSongListById?songListId=${songListVo.songListPo.songlistid}"><button class="layui-btn layui-btn-small"><i class="layui-icon"></i></button></a>
<a href="deleteSongListPo?songListId=${songListVo.songListPo.songlistid}"><button class="layui-btn layui-btn-small"><i class="layui-icon"></i></button></td>
</tr>
</c:forEach>
</tbody>
</table>
<div id="ul"></div>
</div>
var pageCount=5*${pageBasePo.pageCount};
laypage.render({
elem: 'ul',
count:pageCount ,
limit:5,
first: '首页',
last: '尾页',
prev: '<em>←</em>',
next: '<em>→</em>',
jump: function(obj, first){//页面跳转执行函数
var search=$("#search").val();
var pageIndex =obj.curr;//当前页码
if(!first){ //首次不执行
$.get(//ajax刷新数据
"getPageSongList",
{search:search,pageIndex:pageIndex},
function(data){
$(".tb").html("");//清空子节点
data.list.forEach(function(value,index){//数据渲染
//控制台输出测试 console.log(value);
var $tr=$('<tr><td><img src="..'+value.songListPo.imgurl+'"/></td>'
+'<td>'+value.songListPo.songlistname+'</td>'
+'<td>'+value.songListPo.accesscount+'</td>'
+'<td>'+value.songListPo.collectioncount+'</td>'
+'<td>'+value.songListPo.tags+'</td>'
+'<td><a href="getSongListById?songListId='+value.songListPo.songlistid+'">
<button class="layui-btn layui-btn-small"><i class="layui-icon"></i><button></a>'
+'<a href="deleteSongListPo?songListId='+value.songListPo.songlistid+'">
<button data-method="confirmTrans" class="layui-btn layui-btn-small"><i class="layui-icon"></i><button></td></tr>');
$(".tb").append($tr);
});
}
);
}
}
});
});
3.我们来看下页面的效果(本人用的LayUI框架)
4.可能描述的有点不太详细,但是对于项目而言确实是有点头疼的有时候碰