您好,登錄后才能下訂單哦!
本文實例為大家分享了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> <h2 align="center">圖片上傳與下載</h2> <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、文件結構
6、在Tomcat上運行的最終成果:
URL:http://localhost:8080/thumbnail/images
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。