SSM结合Ajax实现文件上传及分页

1.运行环境

myeclipse+mysql+jdk1.7
Sping、SpingMVC、Mybatis三大框架的必要jar包。
当然必要的还有文件上传的jar包
讲下小编最近在做的一个实训项目:MC音乐在线网站,因为本人主要负责后台的编写,而歌曲少不了文件的上传和下载,但是文件上传在我的分工中有,所以这里我就只写我写的文件上传。其实下载也差不多,后续可能补上!!

SSM结合Ajax实现文件上传及分页_第1张图片

就我选中的两个包!!!!!!!!!!!!!!!!!!!!

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 FileDown(List 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 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(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 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 getPageSongList(String search,Integer pageIndex){

		SongListVo songListVo=new SongListVo();
		
		SongListPo songListPo=new SongListPo();
		
		if(search!=null)
		{
		songListPo.setSonglistname(search);
		}

		songListVo.setSongListPo(songListPo);
		
		PageBasePo pageBasePo=adminSongListServiceImpl.filter1(songListVo, 5, pageIndex);
		
		return pageBasePo;
				
		
	}			
}
建议在后台传给前台的JSON对象的时候是分页对象,这样方便在前台取值,也好数据回显。。。

2.3下面来看前台页面

歌单封面 歌单名称 歌单热度 收藏次数 标签 操作
${songListVo.songListPo.songlistname} ${songListVo.songListPo.accesscount} ${songListVo.songListPo.collectioncount} ${songListVo.songListPo.tags}
  			var pageCount=5*${pageBasePo.pageCount};
               
				laypage.render({
				elem: 'ul',
				count:pageCount ,
				limit:5,
				first: '首页',
				last: '尾页',
				prev: '',
				next: '',
				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=$(''
					+''+value.songListPo.songlistname+''
					+''+value.songListPo.accesscount+''
					+''+value.songListPo.collectioncount+''
					+''+value.songListPo.tags+''
					+'


 
  

3.我们来看下页面的效果(本人用的LayUI框架)

4.可能描述的有点不太详细,但是对于项目而言确实是有点头疼的有时候碰

 
   
 
   

到文件上传的时候,其实原理是可以参照SpringMVC的文件上传的,如果不太懂也可以私信问我哦!!!!














你可能感兴趣的:(三大框架整合)