摘要:SpringMvc中的单多文件上传及文件下载:(以下是核心代码(拿过去直接能用)不谢)

<!--设置文件上传需要的jar-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

ControllerWelcome 控制器类:

package controller;
import bean.User;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.RandomUtils;
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.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* @author asus
*/
@Controller
@RequestMapping("/user")
public class ControllerWelcome {   //单文件上传(User对象的属性名与表单中的name名一致方可自动映射到值)
@RequestMapping("/upload")
public ModelAndView upload(User user, MultipartFile picPath, HttpSession session) {
ModelAndView modelAndView = new ModelAndView("Welcome");
//获取服务器路径
String realPath = session.getServletContext().getRealPath("/upload/");
//判断是否存在,不存在则创建
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
//获取源文件名称
String originalFilename = picPath.getOriginalFilename();
String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + originalFilename;
File file1 = new File(realPath, fileName);
try {
picPath.transferTo(file1);
System.out.println("用户名为:" + user.getUseName());
System.out.println("上传成功:" + realPath);
} catch (IOException e) {
e.printStackTrace();
}
return modelAndView;
}
  //多文件上传(User对象中的属性名与表单的name名一致方可自动映射到值)
@RequestMapping("/uploads")
public ModelAndView uploads(User user, @RequestParam MultipartFile[] picPath, HttpSession session) {
ModelAndView modelAndView = new ModelAndView("Welcome");
//获取服务器路径
String realPath = session.getServletContext().getRealPath("/upload/");
//判断是否存在,不存在则创建
File file = new File(realPath);
if (!file.exists()) {
file.mkdir();
}
for (MultipartFile temp : picPath) {
//获取源文件名称
String originalFilename = temp.getOriginalFilename();
String fileName = System.currentTimeMillis() + RandomUtils.nextInt(0, 1000000) + originalFilename;
File file1 = new File(realPath, fileName);
try {
temp.transferTo(file1);
System.out.println("用户名为:" + user.getUseName());
System.out.println("上传成功:" + realPath);
} catch (IOException e) {
e.printStackTrace();
}
}
return modelAndView;
} //文件下载
@RequestMapping(value = "/download", method = RequestMethod.GET) //匹配的是href中的download请求
public ResponseEntity<byte[]> download(@RequestParam("filename") String filename
) throws IOException {
//从我们的上传文件夹中去取
String downloadFilePath = "E:\\idealCase\\CourseNotes\\SpringMvcCase\\SpringMvcCode06\\target\\SpringMvcCode06\\upload";
//新建一个文件
File file = new File(downloadFilePath + File.separator + filename);
//http头信息
HttpHeaders headers = new HttpHeaders();
//设置编码
String downloadFileName = new String(filename.getBytes("UTF-8"), "iso-8859-1"); headers.setContentDispositionFormData("attachment", downloadFileName); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息 return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED); }
}

核心配置文件:Spring-view.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!--指定Controller扫描器-->
<context:component-scan base-package="controller"/>
<!--配置试图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
<property name="suffix" value=".jsp"></property>
</bean> <!--配置文件上传解析器-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"/>
<!--单个文件大小-->
<property name="maxUploadSizePerFile" value="100000"/>
<!--文件总大小-->
<property name="maxUploadSize" value="100000"/>
</bean> </beans>

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>
<display-name>Archetype Created Web Application</display-name>
<!--设置乱码-->
<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>
<!--设置核心控制器-->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:Spring-*.xml</param-value>
</init-param>
<!--优先加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

index.jsp 前端页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<body>
<h2>Hello World!</h2>
<fieldset>
<legend>单文件上传:</legend>
<form action="/user/upload" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="useName"><br/>
文件一:<input type="file" name="picPath">
<input type="submit" value="提交">
</form>
</fieldset>
<br/><br/>
<fieldset>
<legend>多文件上传:</legend>
<form action="/user/uploads" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="useName"><br/>
文件一:<input type="file" name="picPath">
文件一:<input type="file" name="picPath">
<input type="submit" value="提交">
</form>
</fieldset>
<br/><br/>
<fieldset>
<legend>文件下载</legend>
<a href="/user/download?filename=1537854894247新建文本文档.txt">
文件下载:1537854894247新建文本文档.txt</a>
</fieldset>
</body>
</html>

分享知识-快乐自己:SpringMvc中的单多文件上传及文件下载的更多相关文章

  1. SpringMVC中使用 MultipartFile 进行文件上传下载及删除

    一:引入必要的包 <!--文件上传--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fil ...

  2. SpringMVC中使用CommonsMultipartResolver进行文件上传

    概述: CommonsMultipartResolver是基于Apache的Commons FileUpload来实现文件上传功能的.所以在项目中需要相应的jar文件. FileUpload版本要求1 ...

  3. Struts2文件上传(基于表单的文件上传)

    •Commons-FileUpload组件 –Commons是Apache开放源代码组织的一个Java子项目,其中的FileUpload是用来处理HTTP文件上传的子项目   •Commons-Fil ...

  4. [原创]java WEB学习笔记49:文件上传基础,基于表单的文件上传,使用fileuoload 组件

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

  5. SpringMVC(四)-- springmvc的系统学习之文件上传、ajax&json处理

    资源:尚学堂 邹波 springmvc框架视频 一.文件上传 1.步骤: (1)导入jar包 commons-fileupload,commons-io (2)在springmvc的配置文件中配置解析 ...

  6. zt对于C#中的FileUpload解决文件上传大小限制的问题设置

    对于C#中的FileUpload解决文件上传大小限制的问题设置 您可能没意识到,但对于可以使用该技术上载的文件的大小存在限制.默认情况下,使用 FileUpload 控件上载到服务器的文件最大为 4M ...

  7. SpringMVC之单/多文件上传

    1.准备jar包(图标所指必备包,其他按情况导入) 2.项目结构 3.SingleController.java(控制器代码单文件和多文件) package com.wt.uplaod; import ...

  8. 分享知识-快乐自己:Struts2文件上传及文件下载

    1)Struts2单文件上传 action:类文件 package com.mlq.action; import com.opensymphony.xwork2.ActionSupport; impo ...

  9. SpringMVC(三)-- 视图和视图解析器、数据格式化标签、数据类型转换、SpringMVC处理JSON数据、文件上传

    1.视图和视图解析器 请求处理方法执行完成后,最终返回一个 ModelAndView 对象 对于那些返回 String,View 或 ModeMap 等类型的处理方法,SpringMVC 也会在内部将 ...

随机推荐

  1. React15.6.0实现Modal弹层组件

    代码地址如下:http://www.demodashi.com/demo/12315.html 注:本文Demo环境使用的是我平时开发用的配置:这里是地址. 本文适合对象 了解React. 使用过we ...

  2. ASP.NET MVC深入浅出系列(持续更新) ORM系列之Entity FrameWork详解(持续更新) 第十六节:语法总结(3)(C#6.0和C#7.0新语法) 第三节:深度剖析各类数据结构(Array、List、Queue、Stack)及线程安全问题和yeild关键字 各种通讯连接方式 设计模式篇 第十二节: 总结Quartz.Net几种部署模式(IIS、Exe、服务部署【借

    ASP.NET MVC深入浅出系列(持续更新)   一. ASP.NET体系 从事.Net开发以来,最先接触的Web开发框架是Asp.Net WebForm,该框架高度封装,为了隐藏Http的无状态模 ...

  3. 朴素贝叶斯分类算法-----java

    1.贝叶斯分类的基础--贝叶斯定理 已知某条件概率.怎样得到两个事件交换后的概率,也就是在已知P(A|B)的情况下怎样求得P(B|A). 这里先解释什么是条件概率: 表示事件B已经发生的前提下,事件A ...

  4. Hibernate学习三----------session详解

    © 版权声明:本文为博主原创文章,转载请注明出处 如何获取session对象 1. openSession 2. getCurrentSession - 如果使用getCurrentSession需要 ...

  5. php的特殊功能-----不是和其他语言比较

    1.header(); 他不只是重定向,和更改字符集 而是发送表头,如 header('HTTP/1.1 404 Not Found   gfdgd'); 可以发送信息给浏览器,让浏览器显示404错误 ...

  6. 14 nginx 中配置 expires缓存提升网站负载

    一:nginx 中配置 expires缓存提升网站负载 对于网站的图片,尤其是新闻站, 图片一旦发布, 改动的可能是非常小的.我们希望 能否在用户访问一次后, 图片缓存在用户的浏览器端,且时间比较长的 ...

  7. OpenCV 入门示例之四:一个简单的变换

    前言 图像的平滑处理,是计算机视觉中非常重要的操作,本文将展示一个可以对图像进行平滑处理的简单程序.而关于平滑处理深层次的知识,会在以后的文章中重点探讨. 代码示例 // 此头文件包含图像IO函数的声 ...

  8. 2_Jsp标签_传统标签功能简介

    1传统标签接口关系:                                   2功能简介                                                   ...

  9. PHP与js之间的交互

    <?php//在php中药想使用jquery,首先需要导入jquery类库 echo "<script src='".base_url('static')." ...

  10. 使用ab 进行并发压力测试

    使用ab 进行并发压力测试 - 参与商 - 博客园 https://www.cnblogs.com/shenshangzz/p/8340640.html 使用ab 进行并发压力测试   ab全称为:a ...