1. 程式人生 > >java後臺開發SpringMVC例子--圖片上傳下載

java後臺開發SpringMVC例子--圖片上傳下載

java後臺開發SpringMVC例子–圖片上傳下載

文章目錄


環境:

win7;jdk1.8_121;tomact8.0;Mysql;spring-4.3.0。需要安裝及配置好jdk,mysql。

完整程式碼下載(需要的jar包已放在lib下)
http://download.csdn.net/download/yhhyhhyhhyhh/9913431

1.配置

連線資料庫需要:mysql-connector-java-5.0.8-bin.jar

伺服器上執行servlet需要:servlet-api.jar

檔案上傳需要:

com.springsource.org.apache.commons.fileupload-1.2.0.jar

com.springsource.org.apache.commons.io-1.4.0.jar

web.xml配置:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>TestOA</display-name>
  <welcome-file-list>
    <welcome-file>/WEB-INF/views/index.jsp</welcome-file>
  </welcome-file-list>
  <servlet>  
        <servlet-name>oa</servlet-name>  
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
        <!-- load-on-startup:表示啟動容器時初始化該Servlet; -->  
        <load-on-startup>1</load-on-startup>  
    </servlet>  
    <servlet-mapping>  
        <servlet-name>oa</servlet-name>  
        <!-- url-pattern:表示哪些請求交給Spring Web MVC處理, “/” 是用來定義預設servlet對映的。 -->  
        <!-- 也可以如“*.html”表示攔截所有以html為副檔名的請求。 -->  
        <url-pattern>/</url-pattern>  
     </servlet-mapping>  
    <!-- 編碼過濾器 --> 
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter </filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/</url-pattern>
    </filter-mapping>
</web-app>

servlet配置(這裡為:oa-servlet.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:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	<!-- spring掃描註解的包 -->
	<context:component-scan base-package="com.springmvc.test" />  
<!-- 在Spring配置檔案中配置ViewResolver -->  
<!-- InternalResourceViewResolver:用於支援Servlet、JSP檢視解析;    
     prefix和suffix:查詢檢視頁面的字首和字尾(字首[邏輯檢視名]字尾),  
     比如傳進來的邏輯檢視名為hello,則該該jsp檢視頁面應該存放在“WEB-INF/views/hello.jsp”;    -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/WEB-INF/views/" />  
        <property name="suffix" value=".jsp" />  
    </bean>  
     <!--檔案上傳解析器配置 -->
    <bean id="multipartResolver"
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 上傳檔案的總大小和單個檔案的大小 -->
    <property name="maxUploadSize" value="12345678900"/>
        <property name="maxInMemorySize" value="10240100"/>
        <property name="defaultEncoding" value="UTF-8"/>
</bean>
</beans>

資料庫資訊:

這裡寫圖片描述

核心程式碼部分。

package com.springmvc.test;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
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.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/*
 * @Controller表示類註解
 * @RequestMapping表示controller指定的URL
 * @RequestParam:根據引數名從URL中取得引數值
 */
@Controller
public class UpDownLoad {
	@RequestMapping("/login")  
	 public String login(@RequestParam("username") String name, @RequestParam("password") String pass,
	            Model model) {  
		 LoginModel newModel=new LoginModel();
		newModel.setName(name);
		newModel.setPas(pass);
		if(newModel.login())
		{
			model.addAttribute("username", name);//傳遞引數
		    return "menu";
		}
		else
		{   model.addAttribute("username", name);
		    return "index";
		}
	  }
	     @RequestMapping("/fileupload")
	     public String upload(@RequestParam("image") CommonsMultipartFile image ,
	    		 HttpServletRequest request) throws IllegalStateException, IOException  {
	         //解析路徑
	         String imgFolder =request.getSession().getServletContext().getRealPath("/fileupload");
	         //解析檔名
	         String imgUrl = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+image.getOriginalFilename();
	         //新建file物件
	         File targetImg = new File(imgFolder ,imgUrl);
	        	 String type=null;// 檔案型別
	        	 type=imgUrl.indexOf(".")!=-1?imgUrl.substring(imgUrl.lastIndexOf(".")+1, imgUrl.length()):null;
	        	 if (type!=null) 
	        	 {// 判斷檔案型別是否為空
	        		 
	        	 if ("GIF".equals(type.toUpperCase())||"PNG".equals(type.toUpperCase())||"JPG".equals(type.toUpperCase())) 
	        	 {
	    	         //判斷檔案是否存在
	    	         if (!targetImg.exists()){
	    	             targetImg.mkdirs();//不存在新建
	    	         }
	    	        image.transferTo(targetImg);
	    	         return "upsuccess";
	        	 }
	        	 }
	        	 return "upfail";
	     }
	     @RequestMapping("/filedownload")
	     public ResponseEntity<byte[]> download() throws IOException {  
	    	    HttpHeaders headers = new HttpHeaders();  
	    	   // String fileUrl="D:\\test.txt";
	    	   String fileUrl="D:\\test.jpg";
	    	    File file= new File(fileUrl);
	    	    headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);  
	    	    String charset=new String(fileUrl.getBytes("utf-8"),"iso-8859-1");
	    	    headers.setContentDispositionFormData("file", charset);  
	    	    return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),  
	    	                                      headers, HttpStatus.CREATED);
	     } 
}

2.測試

​ 圖片上傳:

這裡寫圖片描述

這裡寫圖片描述
這裡寫圖片描述

圖片下載:
這裡寫圖片描述

檔案下載:
這裡寫圖片描述