SpringMVC框架實(shí)現(xiàn)圖片上傳與下載
本文實(shí)例為大家分享了SpringMVC框架實(shí)現(xiàn)圖片上傳與下載的具體代碼,供大家參考,具體內(nèi)容如下
1、新建一個(gè)Maven webapp項(xiàng)目,引入需要用的夾包,pom.xml文件的依賴包如下:
<dependencies> <!-- 用于生成圖片的縮略圖 --> <dependency> <groupId>net.coobird</groupId> <artifactId>thumbnailator</artifactId> <version>0.4.8</version> </dependency> <!-- 單元測(cè)試包 --> <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標(biāo)簽包,在jsp中使用 --> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> </dependencies>
2、配置文件設(shè)置如下:
(1) web.xml內(nèi)容為:
<?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的前端控制器,可以配置多個(gè)前端控制器來(lái)攔截不同的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文件內(nèi)容為:
<?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的視圖解析器,可以配置多個(gè)viewresolver--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 會(huì)用到EL表達(dá)式以及jstl的標(biāo)簽,必須包含這個(gè)類 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 1、自動(dòng)注冊(cè)defaultAnnotationHandlermapping ,AnnotationMethodhandlerAdapter,可以根據(jù)URL映射到方法--> <!-- 2、數(shù)據(jù)綁定,數(shù)字和日期的format,如@NumberFormat ,@DateFormat,還有xml和json的默認(rèn)讀寫功能 --> <mvc:annotation-driven /> <!-- 1.加入對(duì)靜態(tài)資源的處理 --> <!-- 2.允許使用“/”做整體映射 --> <mvc:default-servlet-handler/> <!-- 自動(dòng)掃描相關(guān)的包 --> <context:component-scan base-package="thumbnail"/> <!-- 對(duì)文件上傳的處理,這里聲明的id必須為multipartResolver--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!-- 最大為100M,單位為字節(jié) --> <property name="maxUploadSize" value="104857600"></property> <property name="defaultEncoding" value="utf-8"></property> <property name="maxInMemorySize" value="40960"></property> </bean> </beans>
3、后端開(kāi)發(fā)
(1) 控制器類:
@Controller @RequestMapping("/") public class ImageController { //使用Autowired時(shí),該業(yè)務(wù)類需要聲明為@service,此時(shí)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 { //根據(jù)相對(duì)路徑獲取絕對(duì)路徑,圖片上傳后位于元數(shù)據(jù)中 String realUploadPath=request.getServletContext().getRealPath("/")+"images"; //獲取上傳后原圖的相對(duì)地址 String imageUrl=upload.uploadImage(file, realUploadPath); //獲取生成的縮略圖的相對(duì)地址 String thumbImageUrl=thumbnail.generateThumbnail(file, realUploadPath); return "redirect:/images"; } //顯示所有圖片 @RequestMapping(value="/images",method=RequestMethod.GET) public ModelAndView showImages(HttpServletRequest request,HttpServletResponse response) { //根據(jù)相對(duì)路徑獲取絕對(duì)路徑,圖片上傳后位于元數(shù)據(jù)中 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()){ //設(shè)置MIME類型 response.setContentType("application/octet-stream"); //或者為response.setContentType("application/x-msdownload"); //設(shè)置頭信息,設(shè)置文件下載時(shí)的默認(rèn)文件名,同時(shí)解決中文名亂碼問(wèn)題 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)業(yè)務(wù)類:
@Service public class Upload { /* * 上傳圖片并返回圖片的相對(duì)地址 */ public String uploadImage(CommonsMultipartFile file,String realUploadPath) throws IOException { //如果目錄不存在則創(chuàng)建目錄 File uploadFile=new File(realUploadPath+"/rawImages"); if(!uploadFile.exists()){ uploadFile.mkdirs(); } //創(chuàng)建輸入流 InputStream inputStream=file.getInputStream(); //生成輸出地址URL String outputPath=realUploadPath+"/rawImages/"+file.getOriginalFilename(); //創(chuàng)建輸出流 OutputStream outputStream=new FileOutputStream(outputPath); //設(shè)置緩沖區(qū) byte[] buffer=new byte[1024]; //輸入流讀入緩沖區(qū),輸出流從緩沖區(qū)寫出 while((inputStream.read(buffer))>0) { outputStream.write(buffer); } outputStream.close(); //返回原圖上傳后的相對(duì)地址 return "images/rawImages/"+file.getOriginalFilename(); } }
@Service public class Thumbnail { //設(shè)置縮略圖的寬度和高度 public static final int witdth=100; public static final int heigth=100; /* * 生成縮略圖并且返回相對(duì)地址 */ public String generateThumbnail(CommonsMultipartFile file,String realUploadPath) throws IOException { //如果目錄不存在則創(chuàng)建目錄 File uploadFile=new File(realUploadPath+"/thumbImages"); if(!uploadFile.exists()){ uploadFile.mkdirs(); } //縮略圖保存的絕對(duì)地址 String des=realUploadPath+"/thumbImages/"+file.getOriginalFilename(); //生成縮略圖 Thumbnails.of(file.getInputStream()).size(witdth, heigth).toFile(des); //返回縮略圖的相對(duì)地址 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、前端開(kāi)發(fā)
images.jsp的內(nèi)容為:
<%@ 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("請(qǐng)先選擇圖片"); 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、文件結(jié)構(gòu)
6、在Tomcat上運(yùn)行的最終成果:
URL:http://localhost:8080/thumbnail/images
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java Volatile與Synchronized的區(qū)別
這篇文章主要介紹了java Volatile與Synchronized的區(qū)別,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下2020-12-12JSP服務(wù)器端和前端出現(xiàn)亂碼問(wèn)題解決方案
這篇文章主要介紹了JSP服務(wù)器端和前端出現(xiàn)亂碼問(wèn)題解決方案,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02SpringCloud超詳細(xì)講解微服務(wù)網(wǎng)關(guān)Zuul基礎(chǔ)
這篇文章主要介紹了SpringCloud?Zuul微服務(wù)網(wǎng)關(guān),負(fù)載均衡,熔斷和限流,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-10-10使用Idea或Datagrip導(dǎo)入excel數(shù)據(jù)的方法
這篇文章主要介紹了使用Idea或Datagrip導(dǎo)入excel數(shù)據(jù)的方法,本文通過(guò)圖文并茂的形式給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-11-11流讀取導(dǎo)致StringBuilder.toString()亂碼的問(wèn)題及解決
這篇文章主要介紹了流讀取導(dǎo)致StringBuilder.toString()亂碼的問(wèn)題及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11Spring Boot 與 Kotlin 使用Redis數(shù)據(jù)庫(kù)的配置方法
Redis是目前業(yè)界使用最廣泛的內(nèi)存數(shù)據(jù)存儲(chǔ)。下面通過(guò)本文給大家介紹Spring Boot 與 Kotlin 使用Redis數(shù)據(jù)庫(kù)的配置方法,感興趣的朋友一起看看吧2018-01-01