欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2023-11-27 14:40:16
本文实例为大家分享了springmvc框架实现图片上传与下载的具体代码,供大家参考,具体内容如下 1、新建一个maven webapp项目,引入需要用的夹包,pom.xm...

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

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

<dependencies>
 
  <!-- 用于生成图片的缩略图 -->
 <dependency>
  <groupid>net.coobird</groupid>
  <artifactid>thumbnailator</artifactid>
  <version>0.4.8</version>
 </dependency> 
 
  <!-- 单元测试包 -->
  <dependency>
   <groupid>junit</groupid>
   <artifactid>junit</artifactid>
   <version>3.8.1</version>
   <scope>test</scope>
  </dependency>
 
  <!-- springmvc夹包 -->
  <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-webmvc</artifactid>
  <version>4.3.11.release</version>
 </dependency>
 
 <!-- spring核心包,用于依赖注入 -->
 <dependency>
  <groupid>org.springframework</groupid>
  <artifactid>spring-core</artifactid>
  <version>4.3.11.release</version>
 </dependency>
 
 <!-- servlet夹包 -->
 <dependency>
  <groupid>javax.servlet</groupid>
  <artifactid>javax.servlet-api</artifactid>
  <version>3.1.0</version>  
 </dependency>
 
 <!-- javaee包,在jsp文件中使用-->
 <dependency>
  <groupid>javax</groupid>
  <artifactid>javaee-api</artifactid>
  <version>7.0</version>  
 </dependency>
 
 <!-- 文件上传的夹包 ,用于文件上传-->
  <dependency>
  <groupid>commons-fileupload</groupid>
  <artifactid>commons-fileupload</artifactid>
  <version>1.3.1</version>
 </dependency>
 
 <!-- jstl标签包,在jsp中使用 -->
 <dependency>
  <groupid>javax.servlet</groupid>
  <artifactid>jstl</artifactid>
  <version>1.2</version>
 </dependency> 
 
</dependencies>

2、配置文件设置如下:

(1) web.xml内容为:

<?xml version="1.0" encoding="utf-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
   xmlns="http://java.sun.com/xml/ns/javaee" 
   xsi:schemalocation="
   http://java.sun.com/xml/ns/javaee 
   http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> 
 
  <!-- 配置springmvc的前端控制器,可以配置多个前端控制器来拦截不同的url -->  
 <servlet>
  <servlet-name>spring</servlet-name>
  <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class>
  <init-param>
   <param-name>contextconfiglocation</param-name>
   <param-value>classpath:springmvc.xml</param-value>
  </init-param>
  <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
  <servlet-name>spring</servlet-name>
  <url-pattern>/</url-pattern>
 </servlet-mapping> 
 
</web-app>

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

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
  xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"
  xmlns:context="http://www.springframework.org/schema/context" 
  xmlns:mvc="http://www.springframework.org/schema/mvc"
  xsi:schemalocation="
   http://www.springframework.org/schema/mvc 
   http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context-3.2.xsd">
 
 <!-- 配置jsp的视图解析器,可以配置多个viewresolver-->
 <bean class="org.springframework.web.servlet.view.internalresourceviewresolver">
 <!-- 会用到el表达式以及jstl的标签,必须包含这个类 -->
    <property name="viewclass" value="org.springframework.web.servlet.view.jstlview"></property>
  <property name="prefix" value="/" />
  <property name="suffix" value=".jsp" />
 </bean>
 
 <!-- 1、自动注册defaultannotationhandlermapping ,annotationmethodhandleradapter,可以根据url映射到方法-->
 <!-- 2、数据绑定,数字和日期的format,如@numberformat ,@dateformat,还有xml和json的默认读写功能 -->
   <mvc:annotation-driven /> 
   
   <!-- 1.加入对静态资源的处理 -->
   <!-- 2.允许使用“/”做整体映射 -->
   <mvc:default-servlet-handler/>
 
   <!-- 自动扫描相关的包 -->
 <context:component-scan base-package="thumbnail"/> 
 
 <!-- 对文件上传的处理,这里声明的id必须为multipartresolver-->
 <bean id="multipartresolver" class="org.springframework.web.multipart.commons.commonsmultipartresolver" > 
   <!-- 最大为100m,单位为字节 -->
  <property name="maxuploadsize" value="104857600"></property>  
  <property name="defaultencoding" value="utf-8"></property>  
  <property name="maxinmemorysize" value="40960"></property>
 </bean>  
 
</beans>

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<string> rawimageslist=new arraylist<string>(); 
 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<string> printfile(string path) {
 file file = new file(path);
 list<string> images = new arraylist<string>();
 
 // 是文件夹的话
 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" %>
<!doctype html public "-//w3c//dtd html 4.01 transitional//en" "http://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>上传图片</title>
</head>
<body>
<script type="text/javascript">
 function validate()
 {
 var a=document.getelementbyid("file");
 var form=document.getelementbyid("upload");
 if(a.value==""){  
  alert("请先选择图片");
   return false;
 }
 else{
 form.submit();
 } 
 }
 
</script>
<h1 align="center">图片上传与下载</h1>
<p>
 <c:foreach var="image" items="${imagelist}"> 
  <a href="images/rawimages/${image}" rel="external nofollow" target="_blank"><img src="images/thumbimages/${image}" /></a>
  <a href="${pagecontext.request.contextpath}/download?filename=${image}" rel="external nofollow" >${image}</a>  
 </c:foreach> 
</p>
 
<form id="upload" action="${pagecontext.request.contextpath}/thumb" method="post" enctype="multipart/form-data">
 <input id="file" type="file" name="image" id="image" > 
 <input type="button" value="上传" οnclick="validate()">
</form>
 
</body>
</html>

5、文件结构

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

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

url:http://localhost:8080/thumbnail/images

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

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