编写一个请求上传和下载的JSP页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>上传 和 下载</h3> <p style="color: red">${UploadMessage}</p> <form
action="${pageContext.request.contextPath}/upload"
enctype="multipart/form-data"
method="post"
> <p>上传的文件:<input type="file" name="UpFile"></p>
<p>上传:<input type="submit"></p>
</form> <p>下载的文件: <a href="${pageContext.request.contextPath}/download">文件资源</a></p>
</body>
</html>

导入上传工具依赖

Maven坐标

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>

配置SpringMVC提供的文件上传工具类【还是依赖于上面的上传工具】

 <!-- 文件上传配置 id="multipartResolver" 不能乱改 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 请求格式编码 和JSP的pageEncoding一致 统一UTF-8最好 -->
<property name="defaultEncoding" value="UTF-8" /> <!-- 文件上传大小 10M -->
<property name="maxUploadSize" value="10485760" />
<!-- 缓存? -->
<property name="maxInMemorySize" value="40960" />
</bean>

完整的文件控制器

package cn.dai.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder; /**
* @author ArkD42
* @file SpringMVC
* @create 2020 - 05 - 07 - 20:07
*/
@Controller
public class FileController { @PostMapping("/upload")
public String getUploadFile(
@RequestParam("UpFile")CommonsMultipartFile file,
HttpServletRequest request
) throws IOException {
String fileName = file.getOriginalFilename(); if ("".equals(fileName)) {
request.setAttribute("UploadMessage","文件上传失败");
return "forward:/UploadAndDownload.jsp";
} System.out.println("正在检查文件,文件名称:" + fileName); String savePath = "C:\\Users\\Administrator\\Desktop\\"; System.out.println("保存路径:" + savePath); InputStream inputStream = file.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath, fileName)); int len;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer))!= -1 ){
fileOutputStream.write(buffer,0,len);
fileOutputStream.flush();
} fileOutputStream.close();
inputStream.close(); request.setAttribute("UploadMessage","文件上传成功");
return "forward:/UploadAndDownload.jsp";
} @PostMapping("/upload2")
public String getUploadFile2(
@RequestParam("UpFile")CommonsMultipartFile file,
HttpServletRequest request
) throws IOException {
String savePath = "C:\\Users\\Administrator\\Desktop\\";
System.out.println("保存路径:" + savePath);
file.transferTo(new File(savePath + file.getOriginalFilename()));
request.setAttribute("UploadMessage","文件上传成功");
return "forward:/UploadAndDownload.jsp";
} @RequestMapping("/download")
public String download01(
HttpServletRequest request,
HttpServletResponse response
) throws Exception{
String path = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\";
String fileName = "21.jpg"; response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
File file = new File(path + fileName); FileInputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024];
int index = 0; while ((index = inputStream.read(buffer)) != -1){
outputStream.write(buffer,0,index); outputStream.flush();
}
outputStream.close();
inputStream.close();
return "forward:/UploadAndDownload.jsp";
} }


第一种上传方式:

- 获取表单的文件参数的值

- 获取文件名

- 设置存储路径

- 创建文件的输出流,文件实例的读取流

- 读取进内存,写入输出流,输出到路径位置

- 释放资源,转发回下载页面 

    @PostMapping("/upload")
public String getUploadFile(
@RequestParam("UpFile")CommonsMultipartFile file,
HttpServletRequest request
) throws IOException {
String fileName = file.getOriginalFilename(); System.out.println("正在检查文件,文件名称:" + fileName); String savePath = "C:\\Users\\Administrator\\Desktop\\"; System.out.println("保存路径:" + savePath); InputStream inputStream = file.getInputStream(); FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath, fileName)); int len;
byte[] buffer = new byte[1024];
while ((len = inputStream.read(buffer))!= -1 ){
fileOutputStream.write(buffer,0,len);
fileOutputStream.flush();
} fileOutputStream.close();
inputStream.close(); request.setAttribute("UploadMessage","文件上传成功");
return "forward:/UploadAndDownload.jsp";
}

第二种上传方式:

设置好文件名和路径,直接写进去完事了

    @PostMapping("/upload2")
public String getUploadFile2(
@RequestParam("UpFile")CommonsMultipartFile file,
HttpServletRequest request
) throws IOException {
String savePath = "C:\\Users\\Administrator\\Desktop\\";
System.out.println("保存路径:" + savePath);
file.transferTo(new File(savePath + file.getOriginalFilename()));
request.setAttribute("UploadMessage","文件上传成功");
return "forward:/UploadAndDownload.jsp";
}

下载文件

- 找到被下载的文件,路径 + 名称

- 响应头设置

- 创建读取和输出流

- 读取目标文件,写入输出流

- 响应请求

    @RequestMapping("/download")
public String download01(
HttpServletRequest request,
HttpServletResponse response
) throws Exception{
String path = "C:\\Users\\Administrator\\Pictures\\Saved Pictures\\";
String fileName = "21.jpg"; response.reset();
response.setCharacterEncoding("UTF-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition","attachment;fileName=" + URLEncoder.encode(fileName,"utf-8"));
File file = new File(path + fileName); FileInputStream inputStream = new FileInputStream(file);
ServletOutputStream outputStream = response.getOutputStream(); byte[] buffer = new byte[1024];
int index = 0; while ((index = inputStream.read(buffer)) != -1){
outputStream.write(buffer,0,index); outputStream.flush();
}
outputStream.close();
inputStream.close();
return "forward:/UploadAndDownload.jsp";
}

【SpringMVC】12 文件上传和下载的更多相关文章

  1. SpringMVC 实现文件上传与下载,并配置异常页面

    目录 上传文件的表单要求 Spring MVC实现上传文件 需要导入的jar包 配置MultipartResolver解析器 编写接收上传文件的控制器 Spring MVC实现文件下载 下载文件时的h ...

  2. 使用springMVC实现文件上传和下载之环境配置与上传

    最近的项目中用到了文件的上传和下载功能,任务分配给了其他的同时完成.如今项目结束告一段落,我觉着这个功能比较重要,因此特意把它提取出来自己进行了尝试. 一. 基础配置: maven导包及配置pom.x ...

  3. springMvc之文件上传与下载

    我们经常会使用的一个功能是文件下载,既然有文件下载就会有文件上传,下面我们来看一下文件上传是如何实现的 首先准备好一个页面 <style type="text/css"> ...

  4. springmvc之文件上传、下载

    1.接收到的是图片的流时 //上传头像 @RequestMapping(value = "/uploadHeadSculpture", method = RequestMethod ...

  5. SpringMVC的文件上传与下载

    1. 单文件上传 配置jsp页面 <%@ page contentType="text/html;charset=UTF-8" language="java&quo ...

  6. 使用SpringMVC实现文件上传和下载

    文件上传 第一步,加入jar包: commons-fileupload-1.3.1.jar commons-io-2.4.jar 第二步,在SpringMVC配置文件中配置CommonsMultipa ...

  7. 【SpringMVC】文件上传与下载、拦截器、异常处理器

    文件下载 使用ResponseEntity实现下载文件的功能 index.html <!DOCTYPE html> <html lang="en" xmlns:t ...

  8. 使用springMVC实现文件上传和下载之文件下载

    接上一篇,文件下载需要获取下载文件的存储路径,这里只是手动填入,如果是在具体项目中,可以把文件名和上传后的存储路径保存在数据库中.然后增加一个文件列表的页面展示文件名和文件路径,然后点击下载的时候把相 ...

  9. 文件上传和下载(可批量上传)——Spring(二)

    针对SpringMVC的文件上传和下载.下载用之前“文件上传和下载——基础(一)”的依然可以,但是上传功能要修改,这是因为springMVC 都为我们封装好成自己的文件对象了,转换的过程就在我们所配置 ...

  10. 使用Spring MVC实现文件上传与下载

    前段时间做毕业设计的时候,想要完成一个上传文件的功能,后来,虽然在自己本地搭建了一个ftp服务器,然后使用公司的工具完成了一个文档管理系统:但是还是没有找到自己想要的文件上传与下载的方式. 今天看到一 ...

随机推荐

  1. mongodb常用数据库指令

    通过客户端的命令进入到mongodb服务中 mongo命令进入客户端 show dbs  查看数据库 show tables/show collections 查看集合(查看当前库里面的表) db 查 ...

  2. 一文了解 - -> SpringMVC

    一.SpringMVC概述 Spring MVC 是由Spring官方提供的基于MVC设计理念的web框架. SpringMVC是基于Servlet封装的用于实现MVC控制的框架,实现前端和服务端的交 ...

  3. springboot项目中一些小技巧

    一.使用命令创建maven工程 1.例如我们想在IDEA的工作空间目录下E:\Gitee\springboot,创建maven项目,首先先进入该目录下 2.去掉原来的目录,输入cmd,然后回车,进入命 ...

  4. go 1.6 废弃 io/ioutil 包后的替换函数

    go 1.6 废弃 io/ioutil  包后的替换函数 io/ioutil 替代 ioutil.ReadAll -> io.ReadAll ioutil.ReadFile -> os.R ...

  5. 10位,13位时间戳转为C#.NET格式时间 DateTime

    10位,13位时间戳转为C#.NET格式时间 DateTime - public static DateTime ToDateTime( string timestamp) { var tz = Ti ...

  6. NET8中增加的简单适用的DI扩展库Microsoft.Extensions.DependencyInjection.AutoActivation

    这个库提供了在启动期间实例化已注册的单例,而不是在首次使用它时实例化. 单例通常在首次使用时创建,这可能会导致响应传入请求的延迟高于平时.在注册时创建实例有助于防止第一次Request请求的SLA 以 ...

  7. element table根据条件隐藏复选框

    在<el-table>标签加 :cell-class-name="cellClass" 在 <el-table-column type="selecti ...

  8. Javascript高级程序设计第三章 | ch3 | 阅读笔记

    语言基础 语法 标识符 注释 // /* */ 严格模式 // 也可以单独指定在一个函数中进行 'use strict' 语句 语句末尾分号不是必须的,但是最好加上 加上分号方便开发者删除空行压缩代码 ...

  9. spring eureka服务注册配置,排查服务注册上来了,但是请求没有过来。检查是否服务注册配置错误

    spring eureka服务注册配置,排查服务注册上来了,但是请求没有过来.检查是否服务注册配置错误 解决方法: 去掉该配置eureka.instance.hostname = client微服务的 ...

  10. python3读csv文件,出现UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in position 0: invalid con

    使用csv.reader(file)读csv文件时,出现如下错误:UnicodeDecodeError: 'utf-8' codec can't decode byte 0xd0 in positio ...