spring mvc 实现单文件 || 多文件上传

文件上传

    • 1. pom依赖(jar包)
    • 2. 文件上传解析器配置
    • 3. 上传实现
    • 4. 下载||文件展示实现(io流的实现)

项目下载地址
https://github.com/sevenyoungairye/File-Upload

1. pom依赖(jar包)

    <!-- common upload file --><dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.4</version></dependency><!-- common upload io--><dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.5</version></dependency>

2. 文件上传解析器配置

spring-mvc.xml

 <!-- 文件上传解析器 --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!--指定总文件大小 单位: b--><property name="maxUploadSize" value="10000000"/><!--指定单个文件的大小--><property name="maxUploadSizePerFile" value="2000000"/><!--指定编码--><property name="defaultEncoding" value="utf-8"/></bean>

3. 上传实现

  • 页面展示
<%--Created by IntelliJ IDEA.User: echo lovelyDate: 2020/9/5Time: 19:37文件上传测试 demo
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>File Upload Demo..</title>
</head>
<body><form method="post" enctype="multipart/form-data" action="fileUpload1">name: <input type="text" name="name" /> <br/>file: <input type="file" name="fileUpload" /> <br/><input type="submit" value="upload"></form><br/>多文件上传:<form method="post" enctype="multipart/form-data" action="fileUpload2">file1 <input type="file" name="uploadFiles"> <br/>file2 <input type="file" name="uploadFiles"> <br/><input type="submit" value="upload"></form></body>
</html>
  • controller接收文件实现
package com.bitqian.controller;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;import java.io.File;
import java.io.IOException;
import java.util.UUID;/**
* spring mvc 测试文件上传
* @author echo lovely
* @date 2020/9/5 9:21
*/
@Controller
public class FileUploadDemo {@RequestMapping(value = "/fileUpload1")@ResponseBodypublic void upload1(String name, MultipartFile fileUpload) {System.out.println(name);System.out.println(fileUpload);String originalFilename = fileUpload.getOriginalFilename();try {// 将文件保存到文件夹//fileUpload.transferTo(new File("f://Temp//" + originalFilename));String ext = originalFilename.substring(originalFilename.lastIndexOf("."));fileUpload.transferTo(new File("f://Temp//" + UUID.randomUUID() + ext));} catch (IOException e) {e.printStackTrace();}}// 多文件上传..@RequestMapping(value = "/fileUpload2")@ResponseBodypublic void uploadFile2(MultipartFile[] uploadFiles) {String path = "f://temp//";File file = new File(path);// 文件夹不存在创建temp文件夹if (!file.exists())file.mkdirs();if (uploadFiles != null) {for (MultipartFile uploadFile : uploadFiles) {String originalFilename = uploadFile.getOriginalFilename();System.out.println("源文件名:" + originalFilename);// uuid + 文件后缀名String fileName = UUID.randomUUID() +originalFilename.substring(originalFilename.lastIndexOf("."));try {// 上传文件到指定目录uploadFile.transferTo(new File(path + fileName));} catch (IOException e) {e.printStackTrace();}}}}}

4. 下载||文件展示实现(io流的实现)

  • 文件下载
@RequestMapping(value="/download/{id}")
public void downloader(HttpServletResponse resp, @PathVariable(value = "id") int stuId) {StudentInfo stu = stuInfoService.queryOne(stuId);// 图像路径String imgPath = stu.getImgPath();if (imgPath == null)return;// 获取图像名的后缀String suffix = imgPath.substring(imgPath.lastIndexOf("."));// 设置文件 ContentType 自动判断下载类型resp.setContentType("multipart/form-data");// 设置文件头resp.setHeader("Content-Disposition", "attachment;fileName="+UUID.randomUUID() + suffix);FileInputStream fis = null;ServletOutputStream outputStream = null;try {fis = new FileInputStream(new File(imgPath));// 使用流输出到客户端outputStream = resp.getOutputStream();byte[] b = new byte[1024];// 读取到数组里面int read = fis.read(b);while(read != -1) {outputStream.write(b, 0, read);read = fis.read(b);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (outputStream != null)outputStream.close();if (fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}}}
  • 文件展示到页面
/*** 图片展示* @throws IOException */
@RequestMapping("/shwoImg/{id}")
public void shwoImg(@PathVariable(value = "id") int stuId, HttpServletResponse resp) {StudentInfo stu = stuInfoService.queryOne(stuId);// 从数据库中取到图片路径String imgPath = stu.getImgPath();if (imgPath == null)return;// 设置文件展示的类型resp.setContentType("image/jpeg");// 拿到out流ServletOutputStream out = null;// 文件读取FileInputStream fis = null;try {out = resp.getOutputStream();// 读取到文件fis = new FileInputStream(new File(imgPath));// 使用一个byte数组byte[] b = new byte[1024];// 将读取的字节装入byte数组int read = fis.read(b);while (read != -1) {out.write(b, 0, read);read = fis.read(b);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {try {if (fis != null)fis.close();} catch (IOException e) {e.printStackTrace();}try {if (out != null) {out.flush();out.close();}} catch (IOException e) {e.printStackTrace();}}}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/420659.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

前端学习(1186):双向数据绑定

<!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><!-- v-cloak用法 -->&…

浏览器获取正确的scrollTop值

window.pageYOffset 被所有浏览器支持除了 IE 6, IE 7, IE 8, 不关doctype的事&#xff0c; 注IE9 开始支持此属性。 window.scrollY 被Firefox, Google Chrome , Safari支持 不关doctype的事, 注IE9 不支持此属性。 在&#xff08;quirk 模式&#xff09;的时候 document.body…

拦截器,利用拦截器进行登陆权限控制

拦截器&#xff0c;登录权限控制demo1. 拦截器demo2. 登录权限控制地址&#xff1a;https://github.com/sevenyoungairye/spring-mvc-interceptor1. 拦截器demo 什么是拦截器 拦截器基于是aop思想实现的。 针对controller里面的目标方法进行拦截。 对比过滤器是过滤所有请求&…

vue的watch监听

Vue.js 有一个方法 watch&#xff0c;它可以用来监测Vue实例上的数据变动。 如果对应一个对象&#xff0c;键是观察表达式&#xff0c;值是对应回调&#xff0c;值也可以是方法名&#xff0c;或者是对象&#xff0c;包含选项。 <template><div><el-input v-mo…

通过CMD命令行创建和使用Android 模拟器 AVD

进行Android APP测试时&#xff0c;若手持android手机设备稀少的情况下&#xff0c;我们可以通过创建Android模拟器AVD来代替模拟android手机设备&#xff0c;本文就具体介绍如何创建和使用AVD。 1、创建AVD 每个AVD模拟一套虚拟设备来运行Android应用程序。无论…

docker安装-环境阿里OS7安装

docker安装-环境阿里OS7安装 官网地址 第一步 curl -fsSL https://get.docker.com -o get-docker.sh第二步 sh get-docker.sh第三步-- 开启docker systemctl start docker第四步–查看docker版本 docker version欧克

mvc框架异常处理机制

目录1.mvc 框架提供的SimpleMappingExceptionResolver2. 继承HandlerExceptionResolver类&#xff0c;根据controller抛出的异常&#xff0c;进行对应的业务操作项目地址https://github.com/sevenyoungairye/spring-mvc-exception1.mvc 框架提供的SimpleMappingExceptionResolv…

前端学习(1188):事件绑定

<!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><!-- v-cloak用法 -->&…

hibernate基于单表curd

目录1. hibernate框架2. 配置文件实体mapper和hibernate.cfg.xml3. 操作单表增删改查1. hibernate框架 数据持久层的框架 功能定位:专门用来访问数据库,对数据库进行增删改查操作 Hibernate是一个ORM框架 MyBatis MyBatisPlus、JPA&#xff08;springdata jpa&#xff09; O…

前端学习(1189):事件基本使用

<!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><!-- v-cloak用法 -->&…

Selenium - IWebDriver 控制scroll bar到底部

有时候我们需要控制页面滚动条上的滚动条&#xff0c;但滚动条并非页面上的元素&#xff0c;这个时候就需要借助js是来进行操作。一般用到操作滚动条的会两个场景&#xff1a; 注册时的法律条文需要阅读&#xff0c;判断用户是否阅读的标准是&#xff1a;滚动条是否拉到最下方。…

Angular常用命令行和指令

命令行: 命令行含义简写ng new 包名生成项目包ng n 包名ng serve启动项目, 端口号4200ng sng serve --open启动项目 并 在默认浏览器自动打开ng s -ong generate component 组件名生成组件ng g c 组件名ng generate directive 指令名生成指令ng g d 指令名ng generate pipe 管…

前端学习(1190):事件修饰符

传统方式 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Document</title><!-- v-cloak用…

mybatis --入门 单表增删改查-curd

目录1. mybatis 环境搭建2. 实体类映射文件配置&#xff08;写sql&#xff09;3. mybatis核心配置文件 &#xff08;环境配置&#xff09;4. 测试mybatis document https://mybatis.org/mybatis-3/zh/ mybatis in github https://github.com/mybatis/mybatis-3 1. mybatis 环…

ios开发之.pch文件的使用

案例&#xff1a;开源中国iOS客户端 当我们新建一个工程的时候&#xff0c;在Supporting FIles文件下会看到一个以 -Prefix.pch结尾文件的文件&#xff0c;pch全称是“precompiled header”&#xff0c;也就是预编译头文件&#xff0c;该文件里存放的工程中一些不常被修…

循环给对象创建属性名和属性值

4.7号笔记&#xff1a; ​ ① 循环给对象创建属性名和属性值&#xff1a; data.forEach(item > {item.identity identity;})console.log(data);

CWnd与HWND的区别与转换

一、区别HWND是句柄&#xff0c;CWnd是MFC窗体类,CWnd中包含HWND句柄成员对象是m_hWnd.HWND是Windows系统中对所有窗口的一种标识&#xff0c;即窗口句柄。这是一个SDK概念。 CWnd是MFC类库中所有窗口类的基类。微软在MFC中将所有窗口的通用操作都封装到了这个类中&#xff0…

字符串截取后两位,字符串转成数组,再转换位字符串

4.11号笔记 字符串去掉所有空格&#xff0c;转成数组&#xff0c;再转成字符串 var str 你好&#xff01; 世界 * * var arr str.replace(/\s/g, "").split("");//去掉所有空格并转成数组arr.splice(-2, 2); // 从最后面截取两位str arr.join(&q…

mybatis dao实现 || 接口代理方式实现

目录1、mybatis环境搭建2、mybatis dao接口实现3、动态代理方式&#xff0c;只实现Mapper接口mybatis入门单表操作demo mybatis dao层实现1. 实现dao层接口 2. 接口代理方式实现dao代理开发要求&#xff1a;​ Mapper接口开发方法只需要编写Mapper接口&#xff08;相当于dao接…