首页 > 学院 > 开发设计 > 正文

springmvc工程文件上传下载

2019-11-11 01:58:53
字体:
来源:转载
供稿:网友

作为程序员,可能会在不经意间就写出来了一段让自己感到骄傲、欣喜、自豪的垃圾代码.

github已上传:https://github.com/kevindai007/sPRingmvcTestProject

今天想新建一个springmvc工程实现上传下载功能,结果在Idea中折腾了半天才弄好,现在记录一下这填坑的过程

File—new—project 这里写图片描述 然后一直点下一步直到Finish.这是idea会自动新建工程,看到Build success说明工程新建成功,如图 这里写图片描述 现在跑一下这个工程,看能否跑起来 这里写图片描述 这里写图片描述 这里写图片描述 启动tomcat,看到hello world界面说明工程新建成功 这里写图片描述

下面来配置springmvc,首先引入springmvc所需的jar包,在pom.xml中添加以下引用

<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.6.RELEASE</version></dependency><!--jsp要使用到的,开始没加,打开Jsp的时候报错 --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!--文件上传--> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.2</version> </dependency>

然后在web.xml配置springmvc过滤;但在这之前咱们需要稍微更新一下web.xml的版本,可以支持更高级的一些语法,如下:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name></web-app>

然后添加springmvc的servlet

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping></web-app>

该servlet名为springmvc(名称可修改),用于拦截请求(url-pattern为 / ,说明拦截所有请求),并交由Spring MVC的后台控制器来处理。这一项配置是必须的。

为了能够处理中文的post请求,再配置一个encodingFilter,以避免post请求中文出现乱码情况(我开始忘记了,导致提交表单中文乱码):

<!-- 字符过滤 --> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>

到这里web.xml的配置就完成了,下面咱们来一个总体预览

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" ><web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <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> <init-param> <param-name>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping></web-app>

在配置完web.xml后,需在web.xml同级目录下新建 springmvc-servlet.xml(-servlet前面是在servlet里面定义的servlet名): 这里写图片描述

要指定springmvc扫描路径时发现自己需要一个保存controller的包,在src/main下新建一个java文件夹由于存放java代码,这时发现不能在该文件夹下新建java文件,需要进行如下操作: 这里写图片描述 然后在java文件夹下新建com.kevindai.web包,并在该包下新建indexController.java文件,新建过程不赘述,代码如下

package com.kevindai.web;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;/** * Created by daiwenkai on 2017/2/7. */@Controllerpublic class IndexController { @RequestMapping("/") public String index(){ return "index"; }}

好的,回到springmvc-servlet.xml,进行相关配置.首先加入component-scan标签,指明controller所在的包,并扫描其中的注解(需要同时引入context命名空间,后面会给出)

<!--指明 controller 所在包,并扫描其中的注解--><context:component-scan base-package="com.kevindai.web"/>

然后开启注解

<!-- 开启注解 --> <mvc:annotation-driven/>

然后配置视图解析器:

<!--ViewResolver 视图解析器--> <!--用于支持Servlet、JSP视图解析--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean>

这里就是确定controller如何找到视图文件,这里需要详细的说明.在 controller 的一个方法中,返回的字符串定义了所需访问的jsp的名字(如上面的index).在jspViewResolver中,有两个属性,一个是prefix,定义了所需访问的文件路径前缀,另一是suffix,表示要访问的文件的后缀,这里为 .jsp.那么,如果返回字符串是 xxx,SpringMVC就会找到 /WEB-INF/jsp/xxx.jsp 文件. 所以咱们还需要在WEB-INF下新建一个jsp文件夹,并在jsp文件夹下新建index.jsp文件(可以把工程中自带的index.jsp删除掉)

然后因为咱们要做上传功能所以还需要配置文件上传的解析器:

<!-- 上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > </bean>

至此springmvc-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:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--指明 controller 所在包,并扫描其中的注解--> <context:component-scan base-package="com.kevindai.web"/> <!-- 开启注解 --> <mvc:annotation-driven/> <!--ViewResolver 视图解析器--> <!--用于支持Servlet、JSP视图解析--> <bean id="jspViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 上传文件 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" > </bean></beans>

下面修改WEB-INF/jsp/index.jsp页面,form表单中不要忘记加enctype=”multipart/form-data”,代码如下

<%-- Created by IntelliJ IDEA. User: daiwenkai Date: 2017/2/7 Time: 15:34 To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head> <title>package apk</title></head><body><form action="/packagedApk" enctype="multipart/form-data" method="post"> <table> <tr> <td>渠 道 号:</td> <td> <input type="text" name="channelNum" id="channelNum"> </td> </tr> <tr> <td>请选择文件:</td> <td><input type="file" name="fileMsg" id="fileMsg"></td> </tr> <tr> <td> <input type="reset" value="重置"> </td> <td> <input type="submit" value="提交"> </td> </tr> </table></form></body></html>

在IndexController中添加packagedApk()方法,最终代码如下:

package com.kevindai.web;import com.kevindai.pojo.PackageApkPojo;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.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.io.*;/** * Created by daiwenkai on 2017/2/7. */@Controllerpublic class IndexController { @RequestMapping("/") public String index(){ return "index"; } /** * 方法写的很粗糙,就是接收上传文件并保存返回下载文件 * @param packageApkPojo * @return * @throws IOException */ @RequestMapping(value = "/packagedApk") @ResponseBody public ResponseEntity<byte[]> packagedApk(PackageApkPojo packageApkPojo) throws IOException { System.out.println(packageApkPojo.getChannelNum()); InputStream inputStream = packageApkPojo.getFileMsg().getInputStream(); String fileName = packageApkPojo.getFileMsg().getOriginalFilename(); OutputStream outputStream = new FileOutputStream("d:" + File.separator + fileName); byte[] b = new byte[1024]; int c; while((c = inputStream.read(b)) > 0){ outputStream.write(b); } inputStream.close(); outputStream.flush(); outputStream.close(); File file = new File("d:" + File.separator + fileName); String dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1"); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", dfileName); return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED); //return "upload success"; }}

PackageApkPojo.java代码如下

package com.kevindai.pojo;import org.springframework.web.multipart.MultipartFile;/** * Created by daiwenkai on 2017/2/7. */public class PackageApkPojo { private String channelNum; private MultipartFile fileMsg;//与jsp中文件框id保持一致 public String getChannelNum() { return channelNum; } public void setChannelNum(String channelNum) { this.channelNum = channelNum; } public MultipartFile getFileMsg() { return fileMsg; } public void setFileMsg(MultipartFile fileMsg) { this.fileMsg = fileMsg; }}

OK就这么简单的东西也折腾了一上午,填不完的坑啊,mdzz


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表