重庆分公司,新征程启航

为企业提供网站建设、域名注册、服务器等服务

SpringMVC框架实现图片上传与下载

本文实例为大家分享了SpringMVC框架实现图片上传与下载的具体代码,供大家参考,具体内容如下

目前创新互联建站已为上千家的企业提供了网站建设、域名、虚拟空间、网站托管维护、企业网站设计、汾阳网站维护等服务,公司将坚持客户导向、应用为本的策略,正道将秉承"和谐、参与、激情"的文化,与客户和合作伙伴齐心协力一起成长,共同发展。

1、新建一个Maven webapp项目,引入需要用的夹包,pom.xml文件的依赖包如下:


 
  
 
  net.coobird
  thumbnailator
  0.4.8
  
 
  
  
   junit
   junit
   3.8.1
   test
  
 
  
  
  org.springframework
  spring-webmvc
  4.3.11.RELEASE
 
 
 
 
  org.springframework
  spring-core
  4.3.11.RELEASE
 
 
 
 
  javax.servlet
  javax.servlet-api
  3.1.0  
 
 
 
 
  javax
  javaee-api
  7.0  
 
 
 
  
  commons-fileupload
  commons-fileupload
  1.3.1
 
 
 
 
  javax.servlet
  jstl
  1.2
  
 

2、配置文件设置如下:

(1) web.xml内容为:

<?xml version="1.0" encoding="UTF-8"?>
 
 
    
 
  spring
  org.springframework.web.servlet.DispatcherServlet
  
   contextConfigLocation
   classpath:springmvc.xml
  
  1
 
 
  spring
  /
  
 

(2)springmvc.xml文件内容为:

<?xml version="1.0" encoding="UTF-8"?>

 
 
 
 
    
  
  
 
 
 
 
    
   
   
   
   
 
   
  
 
 
  
   
    
    
  
   
 

3、后端开发

(1) 控制器类:

@Controller
@RequestMapping("/")
public class ImageController {
 
 //使用Autowired时,该业务类需要声明为@service,此时xml中不用其它的配置
 @Autowired 
  private Upload upload; 
 @Autowired
  private Thumbnail thumbnail;
 
 //文件上传并生成缩略图
 @RequestMapping(value="/thumb",method=RequestMethod.POST)
 public String GenerateImage(@RequestParam("image")CommonsMultipartFile file,HttpServletRequest request) throws IOException
 { 
 //根据相对路径获取绝对路径,图片上传后位于元数据中
 String realUploadPath=request.getServletContext().getRealPath("/")+"images"; 
 
 //获取上传后原图的相对地址
 String imageUrl=upload.uploadImage(file, realUploadPath);
 
 //获取生成的缩略图的相对地址
 String thumbImageUrl=thumbnail.generateThumbnail(file, realUploadPath); 
 return "redirect:/images";
 }
 
 
 //显示所有图片
 @RequestMapping(value="/images",method=RequestMethod.GET)
 public ModelAndView showImages(HttpServletRequest request,HttpServletResponse response)
 {
 //根据相对路径获取绝对路径,图片上传后位于元数据中
 List rawImagesList=new ArrayList(); 
 String realUploadPath=request.getServletContext().getRealPath("/")+"images"; 
 rawImagesList=ImageList.printFile(realUploadPath+"/rawImages");
 
 ModelAndView mv=new ModelAndView();
 mv.addObject("imageList", rawImagesList);
 mv.setViewName("images");
 return mv;
 }
 
 //文件下载
 @RequestMapping("/download")
 public void download(HttpServletRequest request,HttpServletResponse response) throws IOException
 {
 String path=request.getServletContext().getRealPath("/")+"/images/rawImages/";
 String fileName=request.getParameter("filename");
 File file=new File(path+fileName);
 if(file.exists()){
 //设置MIME类型
 response.setContentType("application/octet-stream"); 
 //或者为response.setContentType("application/x-msdownload");
 
 //设置头信息,设置文件下载时的默认文件名,同时解决中文名乱码问题
 response.addHeader("Content-disposition", "attachment;filename="+new String(fileName.getBytes(), "ISO-8859-1"));
 
 InputStream inputStream=new FileInputStream(file);
 ServletOutputStream outputStream=response.getOutputStream();
 byte[] bs=new byte[1024];
 while((inputStream.read(bs)>0)){
 outputStream.write(bs);
 }
 outputStream.close();
 inputStream.close(); 
 }
 }
}

(2)业务类:

@Service
public class Upload {
 
 /*
 * 上传图片并返回图片的相对地址
 */ 
 public String uploadImage(CommonsMultipartFile file,String realUploadPath) throws IOException
 {
 //如果目录不存在则创建目录
 File uploadFile=new File(realUploadPath+"/rawImages");
 if(!uploadFile.exists()){
 uploadFile.mkdirs();
 } 
 
 //创建输入流
 InputStream inputStream=file.getInputStream();
 //生成输出地址URL
 String outputPath=realUploadPath+"/rawImages/"+file.getOriginalFilename();
 //创建输出流
 OutputStream outputStream=new FileOutputStream(outputPath); 
 //设置缓冲区
 byte[] buffer=new byte[1024];
 
 //输入流读入缓冲区,输出流从缓冲区写出
 while((inputStream.read(buffer))>0)
 {
 outputStream.write(buffer);
 }
 outputStream.close();
 
 //返回原图上传后的相对地址
 return "images/rawImages/"+file.getOriginalFilename();
 }
 
}
@Service
public class Thumbnail {
 
 //设置缩略图的宽度和高度
 public static final int witdth=100;
 public static final int heigth=100;
 
 /* 
 * 生成缩略图并且返回相对地址
 */
 public String generateThumbnail(CommonsMultipartFile file,String realUploadPath) throws IOException
 {
 
 //如果目录不存在则创建目录
 File uploadFile=new File(realUploadPath+"/thumbImages");
 if(!uploadFile.exists()){
 uploadFile.mkdirs();
 } 
 
 //缩略图保存的绝对地址
 String des=realUploadPath+"/thumbImages/"+file.getOriginalFilename();
 //生成缩略图
 Thumbnails.of(file.getInputStream()).size(witdth, heigth).toFile(des);
 //返回缩略图的相对地址
 return "images/thumbImages/"+file.getOriginalFilename();
 }
 
}
public class ImageList {
 
 //获取文件夹下所有文件名
 public static List printFile(String path) {
 File file = new File(path);
 List images = new ArrayList();
 
 // 是文件夹的话
 if (file.isDirectory()) {
 String[] filelist = file.list();
 for (int i = 0; i < filelist.length; i++) {
 File readfile = new File(path + "/" + filelist[i]);
 if (!readfile.isDirectory()) {
  images.add(readfile.getName());
 }
 }
 
 }
 return images;
 }
 
}

4、前端开发

images.jsp的内容为:

<%@ page language="java" contentType="text/html; charset=UTF-8"
 pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




上传图片



图片上传与下载

${image}

5、文件结构

SpringMVC框架实现图片上传与下载

6、在Tomcat上运行的最终成果:

URL:http://localhost:8080/thumbnail/images

SpringMVC框架实现图片上传与下载

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持创新互联。


本文题目:SpringMVC框架实现图片上传与下载
文章转载:http://cqcxhl.cn/article/jecosp.html

其他资讯

在线咨询
服务热线
服务热线:028-86922220
TOP