文件上传
- 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();}}}