编写一个请求上传和下载的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. mysql中,时间类型datetime和timestamp的区别

    TIMESTAMP和DATETIME的相同点: 两者都可用来表示 YYYY-MM-DD HH:MM:SS 类型的日期. TIMESTAMP和DATETIME的不同点: 1>  两者的存储方式不一 ...

  2. golang sync.Once 保证某个动作仅执行一次的机制

    type Once struct { done atomic.Uint32 m Mutex } 这段代码是 Go 语言标准库中 sync 包的一部分,定义了一个 Once 类型.Once 类型用于确保 ...

  3. 使用Wesky.Net.OpenTools包来快速实现嵌套型结构体数据转换功能

    今天遇到有人提到结构体和byte数组互转的问题,我就顺便拿来水一篇.这是一个冷门的问题,估计使用的人不多.既然有需求,应该就有使用场景,那就顺便整一波. 为了达到效果,结构体.复杂结构体嵌套等都能实现 ...

  4. python写文件,过滤空行,根据某一行打上标记

    import shutil import os ###第一步写文件 ''' with open('test.txt', 'w',encoding='utf-8') as f: f.write(&quo ...

  5. 用CSS3绘制iPhone手机

    Tips:当你看到这个提示的时候,说明当前的文章是由原emlog博客系统搬迁至此的,文章发布时间已过于久远,编排和内容不一定完整,还请谅解` 用CSS3绘制iPhone手机 日期:2017-7-3 阿 ...

  6. python 二次封装logging,导致日志输出的filename错误及优化封装

    问题 封装logging文件名称为:A.py 调用A模块的文件名称为:B.py 二次封装了logging日志模块,根据需要,传入level,判断等级,调用logging模块的info.debug等日志 ...

  7. 高通与At指令:AtCop解析

    背景 在某个新基线上移植AT指令,发现有问题,因此收集了这个系列的 文章 作为 这方面的知识补充. 原文作者:laozhuxinlu,本文有删改. 另外,还参考了:https://www.cnblog ...

  8. 哇塞,实测780MB/s!基于RK3568J与FPGA的PCIe通信案例详解

    ARM + FPGA架构有何种优势 近年来,随着中国新基建.中国制造2025的持续推进,单ARM处理器越来越难满足工业现场的功能要求,特别是能源电力.工业控制.智慧医疗等行业通常需要ARM + FPG ...

  9. MAPREDUCE中的序列化

    Java的序列化是一个重量级序列化框架(Serializable),一个对象被序列化后,会附带很多额外的信息(各种校验信息,header,继承体系....),不便于在网络中高效传输: 所以,hadoo ...

  10. 羊城杯初赛部分misc

    羊城杯初赛部分misc Ez_misc i春秋刚考过的CVE,win11截图漏洞CVE-2023-21036(acropalypse) https://github.com/frankthetank- ...