SpringBoot文件上传下载

SpringBoot文件上传下载

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>1.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
	
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.1.1.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>

	<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <fastjson.version>1.2.38</fastjson.version>
    </properties>

	<dependencies>
         <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-web</artifactId>
         </dependency>
         
         <!-- jstl JSP标准标签库  -->
		<dependency>
		    <groupId>javax.servlet</groupId>
		    <artifactId>jstl</artifactId>
		</dependency>
		<!-- 返回jsp页面还需要这个依赖 -->
		<dependency>
		    <groupId>org.apache.tomcat.embed</groupId>
		    <artifactId>tomcat-embed-jasper</artifactId>
		</dependency>

        <!-- fastjson -->
		<dependency>
		    <groupId>com.alibaba</groupId>
		    <artifactId>fastjson</artifactId>
		    <version>${fastjson.version}</version>
		</dependency>
    </dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
application.properties
 server.port=8080
 spring.mvc.view.prefix=/WEB-INF/
 spring.mvc.view.suffix=.jsp
 servlet.multipart.max-file-size=10MB
 servlet.multipart.max-request-size=100MB
user.jsp
<%@ page language="java" pageEncoding="UTF-8" contentType="text/html;charset=utf-8"%>

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>文件上传</title>
</head>
<body>
	<form action="/uploads" method="post" enctype="multipart/form-data">
		<input type="file" name="file1">
		<input type="file" name="file2">
		<input type="text" name="custId">
		<input type="text" name="comments">
		<input type="submit" value="上传">
	</form>
</body>
</html>

简单的写一个上传文件用的页面,这里用的是form表单提交。也可以用formdata等IE10、H5的新方法,这里就不赘述了。

controller
@RestController
public class UserController {

    @RequestMapping("/user")
	public ModelAndView user (){
	    return new ModelAndView("user");
	}

	@RequestMapping("/uploads")
	public String uploads(HttpServletRequest request, String comments, String custId) throws IOException {
		StringBuilder result = new StringBuilder();
		result.append("custId:").append(custId).append(",comments:").append(comments);

    	MultipartHttpServletRequest multipartReq = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartReq.getFileMap();
		for(String key : fileMap.keySet()){
			MultipartFile file = fileMap.get(key);
			if(!file.isEmpty()){
				result.append("key:").append(key).append(",name:").append(file.getOriginalFilename());
			}
		}

		return result.toString();
	}

	@RequestMapping("/upload")
	public String upload(MultipartFile file, String custId, String comments) throws IOException {
		write(file.getBytes(), file.getOriginalFilename());

		//file.getSize()就是file.getBytes().length。也就是说,文件转化为byte[]的长度,单位字节B,占用空间是2^n
		return String.valueOf(file.getSize());
	}

	@RequestMapping("/download")
	public void download(HttpServletResponse response) throws IOException {
    	String fileName = "sso-url.txt";		//如果文件名是中文的,需要根据浏览器进行转码

		response.setContentType("application/force-download;charset=UTF-8");
		response.setHeader("Content-disposition", "attachment; filename=" + fileName);

		OutputStream out = response.getOutputStream();
		out.write(read(fileName));
	}

	private void write(byte[] bytes, String fileName){
		FileOutputStream fos = null;
		BufferedOutputStream bos = null;

		try {
			File dir = new File("D://"+fileName);
			if(!dir.exists() && dir.isDirectory()){
				dir.mkdirs();
			}
			fos = new FileOutputStream(dir);
			bos = new BufferedOutputStream(fos);
			bos.write(bytes);
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(null!=bos){
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=fos){
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

	private byte[] read(String fileName){
		byte[] result = null;

		InputStream in = null;
		ByteArrayOutputStream out = null;
		try {
			in = new FileInputStream("D://"+fileName);
			out = new ByteArrayOutputStream();
			byte[] buffer = new byte[10240];
			int n = 0;
			while ((n = in.read(buffer)) != -1) {
				out.write(buffer, 0, n);
			}
			result = out.toByteArray();
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			if(null!=out){
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(null!=in){
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return result;
	}

}
启动类
@SpringBootApplication
public class DemoApplication {

	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}

}
项目结构

在这里插入图片描述
启动。访问http://127.0.0.1:8080/user进入文件上传页面,选择文件并点击上传。
在这里插入图片描述
这里截图是用的单个文件上传,看controller和jsp中添加了多个文件上传的方式,顺便也随便加了点其他参数。
在这里插入图片描述
返回的数字是该文件的大小,2446字节,大于2^10(2048B),
所以占用空间是2^11(4096B)。
在这里插入图片描述
再访问http://127.0.0.1:8080/download下载该文件,这里文件名我固定了。
就完成了整个文件的上传和下载流程。顺便提一下,如果文件要放入mysql数据库,可以用blob类型保存,我用的是mediumblob最大16M,实体类对应的是byte[]。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值