springboot上传和下载

第一步:创建spirngboot工程并引入依赖

Pom文件:

<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.2.0.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>tkgg.upload</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>1.18.10</version>
		</dependency>
		<dependency>
			<groupId>com.google.guava</groupId>
			<artifactId>guava</artifactId>
			<version>28.1-jre</version>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
			<exclusions>
				<exclusion>
					<groupId>org.junit.vintage</groupId>
					<artifactId>junit-vintage-engine</artifactId>
				</exclusion>
			</exclusions>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
	</dependencies>

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

</project>

Controoler类:

package tkgg.upload.demo.controller;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Encoder;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Base64;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {

    @RequestMapping("/index")
    public String index(){
        return "Success";
    }

    @PostMapping("/upload")
    public String upload2(@RequestParam(value = "file",required = true) MultipartFile file){
        if(file.isEmpty()){
            log.error("文件不存在,请选择文件");
            return "文件不存在,请选择文件";
        }

        ArrayList<String> imageType = Lists.newArrayList("jpg", "jpeg", "bmp", "png", "gif");
        String originalFilename = file.getOriginalFilename();
        String suffixName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        originalFilename = Base64.getEncoder().encodeToString(originalFilename.getBytes());
        originalFilename = originalFilename + UUID.randomUUID().toString().replace("-","");

        if(imageType.contains(suffixName.toLowerCase())){
            int code = originalFilename.hashCode();
            String hexString = Integer.toHexString(code);
            File saveDir = new File("F:" + File.separator + hexString.charAt(0) + File.separator + hexString.charAt(1));
            if(!saveDir.exists()){
                saveDir.mkdirs();
            }
            File destPath = new File(saveDir,originalFilename + "." + suffixName);
            try {
                file.transferTo(destPath);
                return destPath.toString();
            } catch (IOException e) {
                log.error(e.toString());
                throw new RuntimeException(e);
            }
        }else{
            log.error("类型不存在");
            return "类型不存在";
        }

    }


    @GetMapping("/downLoad")
    public void downLoad(HttpServletRequest request, HttpServletResponse response) throws IOException {

        /*
         * 两个头一个流
         * 1. Content-Type
         * 2. Content-Disposition
         * 3. 流:下载文件的数据
         */
        String file = "F:\\4\\5\\截图.png";
        int index = file.lastIndexOf("\\");
        String filePath = file.substring(0,index + 1);
        String fileName = file.substring(index + 1);

        //为了使下载框中显示中文文件名称不出乱码!
        String frameName = URLEncoder.encode(fileName, "utf-8");

        //为了兼容各种浏览器使下载框中显示中文文件名称不出乱码!
//        String frameName = filenameEncoding(fileName, request);

        //通过文件名称获取MIME类型
        String contentType = request.getServletContext().getMimeType(fileName);
        String contentDisposition = "attachment;filename=" + frameName;

        // 一个流
        FileInputStream input = new FileInputStream(filePath + fileName);

        //设置两个头
        response.setHeader("Content-Type", contentType);
        response.setHeader("Content-Disposition", contentDisposition);

        // 获取绑定了响应端的流
        ServletOutputStream output = response.getOutputStream();

        FileCopyUtils.copy(input, output);//把输入流中的数据写入到输出流中。

        input.close();

    }

    // 用来对下载的文件名称进行编码的!
    private static String filenameEncoding(String filename, HttpServletRequest request) throws IOException {
        String agent = request.getHeader("User-Agent"); //获取浏览器
        if (agent.contains("Firefox")) {
            BASE64Encoder base64Encoder = new BASE64Encoder();
            filename = "=?utf-8?B?"
                    + base64Encoder.encode(filename.getBytes("utf-8"))
                    + "?=";
        } else if(agent.contains("MSIE")) {
            filename = URLEncoder.encode(filename, "utf-8");
        } else {
            filename = URLEncoder.encode(filename, "utf-8");
        }
        return filename;
    }

}

html文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file" value="请选择文件"/>
        <p></p>
        <input type="submit" value="点击上传"/>
    </form>

</body>
</html>

application.properties文件

server.port=8989

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值