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

java后台开发SpringMVC例子--图片上传下载

程序员文章站 2022-06-02 14:06:33
...

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>

数据库信息:

java后台开发SpringMVC例子--图片上传下载

核心代码部分。

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.测试

​ 图片上传:

java后台开发SpringMVC例子--图片上传下载

java后台开发SpringMVC例子--图片上传下载
java后台开发SpringMVC例子--图片上传下载

图片下载:
java后台开发SpringMVC例子--图片上传下载

文件下载:
java后台开发SpringMVC例子--图片上传下载