Spring Boot Road Primer (12) --- Spring Boot for file upload and download files

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Geffin/article/details/100588512

1 file upload

Implement the controller

package edu.szu.test.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

@Controller
@RequestMapping("/upload")
public class FileController {
    
    //单文件上传
    @RequestMapping("/little")
    @ResponseBody
    public String upload(@RequestParam("file1") MultipartFile file) {
        if (file.isEmpty()) {
            return "空文件";
        }
        // 获取文件名
        String fileName = file.getOriginalFilename();
        // 文件上传后的路径
        String filePath = "D://javatest//";
        File dest = new File(filePath + fileName);
        // 检测是否存在目录
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest);
            return "单文件上传成功";
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "单文件上传失败";
    }

    //多文件上传
    @RequestMapping("/many")
    @ResponseBody
    public String handleFileUpload(HttpServletRequest request) {
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("file2");
        MultipartFile file = null;
        BufferedOutputStream stream = null;
        for (int i = 0; i < files.size(); ++i) {
            file = files.get(i);
            if (!file.isEmpty()) {
                try {
                	// 获取文件名
                    String fileName = file.getOriginalFilename();
                    // 文件上传后的路径
                    String filePath = "D://javatest//";
                    byte[] bytes = file.getBytes();
                    stream = new BufferedOutputStream(new FileOutputStream(
                            new File(filePath + fileName)));
                    stream.write(bytes);
                    stream.close();
                } catch (Exception e) {
                    stream = null;
                    return "上传第" + i + "个文件失败";
                }
            } else {
                return "第 " + i + "个文件为空";
            }
        }
        return "多文件上传成功";
    }
}

Create a file upload page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
    <title>文件上传测试</title>
</head>
<body>
<p>单文件上传测试</p>
<form action="/upload/little" method="POST" enctype="multipart/form-data">
    请选择你需要上传的单文件:<input type="file" name="file1"/>
    <input type="submit" value="点我提交"/>
</form>
<p>多文件上传测试</p>
<form action="/upload/many" method="POST" enctype="multipart/form-data">
    <p>请选择你需要上传的文件1:<input type="file" name="file2"/></p>
    <p>请选择你需要上传的文件2:<input type="file" name="file2"/></p>
    <p><input type="submit" value="点我提交" /></p>
</form>
</html>

Modify application.properties

# 指定端口
server.port=8080
# 页面默认前缀目录
spring.mvc.view.prefix=/WEB-INF/jsp/
# 响应页面默认后缀
spring.mvc.view.suffix=.jsp

# 上传文件总的最大值
spring.servlet.multipart.max-request-size=10MB
# 单个文件的最大值
spring.servlet.multipart.max-file-size=1MB

test

Open the page
Here Insert Picture Description
select Add a picture
Here Insert Picture Description
to submit
Here Insert Picture Description
findings show that successful upload on a web page, and then we open javatest folder, find the picture has been added to it, and to prove our file upload function has been successfully achieved.
Here Insert Picture Description

2 file download

Implement the controller

package edu.szu.test.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class FileController {
    
	//文件下载功能的实现
	@RequestMapping("/download")
	public void download(HttpServletResponse res ) {
		String fileName = "img.jpg";
 
		res.setHeader("content-type", "application/octet-stream");
		res.setContentType("application/octet-stream");
		res.setHeader("Content-Disposition", "attachment; filename=" + fileName);
		byte[] buff = new byte[1024];
		BufferedInputStream bis = null;
		OutputStream os = null;
 
		try {
			os = res.getOutputStream();
			bis = new BufferedInputStream(new FileInputStream(new File("d://javatest//" + fileName )));
			int i = bis.read(buff);
 
			while (i != -1) {
				os.write(buff, 0, buff.length);
				os.flush();
				i = bis.read(buff);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (bis != null) {
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
  }
}

Create a file download page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8" />
    <title>文件下载测试</title>
</head>
<body>
<a href="http://localhost:8080/download">点我开始下载文件img.jpg</a>
</html>

test

Open the page
Here Insert Picture Description
click download, find the file really has been downloaded to the machine, to prove our file download function to achieve success.
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/Geffin/article/details/100588512