SpringMvc的文件的上传下载

我的pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com</groupId>
  <artifactId>SpringMvc</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  
  <build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build>
  
  <dependencies>
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-context</artifactId>
  <version>4.3.8.RELEASE</version>
  </dependency>
  <dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>4.3.8.RELEASE</version>
  </dependency>
  <dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>jsp-api</artifactId>
  <version>2.1</version>
  <scope>provided</scope>
  </dependency>
  <dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
  <scope>provided</scope>
  </dependency>
  <dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
  </dependency>
  <dependency>
  <groupId>taglibs</groupId>
  <artifactId>standard</artifactId>
  <version>1.1.2</version>
  </dependency>
  <dependency>
  <groupId>commons-io</groupId>
  <artifactId>commons-io</artifactId>
  <version>2.4</version>
  </dependency>
  <dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.1</version>
  </dependency>
  </dependencies>

</project>


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">
  <display-name>SpringMvc</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <!-- 前端控制器 -->
<servlet>
<servlet-name>frontController</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>


<servlet-mapping>
<servlet-name>frontController</servlet-name>
<url-pattern>/</url-pattern><!-- /* 包含.jsp     /不包含 .jsp-->
</servlet-mapping>

</web-app>


我的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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" 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-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

<!-- 默认扫描的包路径 -->
<context:component-scan base-package="com.upload.controller"></context:component-scan>
<mvc:annotation-driven/>


<!-- 映射处理器 -->
<!--  <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"></bean> --> 
<!--处理适配器 -->
<!-- <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"></bean> --> 
<!-- 视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView"></property>
<property name="prefix" value="/WEB-INF/jsp/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000" />
<property name="defaultEncoding" value="UTF-8" />
</bean>

</beans>


我的jsp页面 

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!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>
<h1>文件上传</h1>
<form action="fileupload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="上传">
</form>
<form action="downloadFile">
<input type="submit" value="下载">
</form>
</body>
</html>

我的controller控制器

package com.upload.controller;


import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;


@Controller
public class UploadController{

public static final String SAVE_PATH = "F:" + "\\" + "uploadfiles" ;



/**
* 文件上传   已经测试过   一切OK  上传到 F盘下面的uploadfiles文件夹下
* @param file
* @param HttpServletRequest
* @return
*/
@RequestMapping("/fileupload")
public String doUpload(MultipartFile file,HttpServletRequest HttpServletRequest){

      

        String newUploadFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()).toString()
+ new Random().nextInt(10);   // newUploadFileName =  201803172356597 获取系统当前时间的毫秒数
        String uploadFileName = file.getOriginalFilename(); // uploadFileName =  java基础知识总结 蓝皮书.doc
        // 截取上传文件的后缀       uploadFileSuffix  =  doc 
        String uploadFileSuffix = uploadFileName.substring(uploadFileName.indexOf('.') + 1, uploadFileName.length());
        
        FileOutputStream fos = null;
FileInputStream fis = null;
// 设置本地储存文件路径
File saveFile = new File(SAVE_PATH);   //  saveFile =  F:\ uploadfiles   中间没有空格是为了防止报错
String savePath = saveFile + "\\" + newUploadFileName + "." + uploadFileSuffix;

System.out.println(savePath);
if (saveFile.exists()) {
try {
fis = (FileInputStream) file.getInputStream();
fos = new FileOutputStream(new File(savePath));
byte[] temp = new byte[1024];
int i = fis.read(temp);
while (i != -1) {
fos.write(temp, 0, temp.length);
fos.flush();
i = fis.read(temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}


// String path = File.separator + "uploadfiles" + File.separator + newUploadFileName + "." + uploadFileSuffix;

/**
* path  =   \     +   uploadfiles  +   \   +  201803172337151  +  .  + doc
* path的输出结果
* */


//把savePath中的 "\"转换成 "\\"
String path = savePath.replaceAll("\\\\", "\\\\\\\\");
System.out.println("path==="+path);  


return "hello";

}

@RequestMapping("/downloadFile")
public void downloadFile(HttpServletResponse response) throws IOException{
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");  //MIME类型
//下载文件的名字和编码方式
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("java资料.doc","utf-8"));
byte[] buff = new byte[1024];
BufferedInputStream bis = null;
OutputStream os = null;
try {
os = response.getOutputStream();
bis = new BufferedInputStream(new FileInputStream(new File("F:\\uploadfiles\\201803180011249.doc")));
int i = bis.read(buff);
while (i != -1) {
os.write(buff, 0, buff.length);
os.flush();
i = bis.read(buff);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值