Springboot实现文件的上传以及下载

编写test.html模板:

<!DOCTYPE html>
<html lang="zh" xmlns="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>动态添加文件上传列表</title>
    <script th:src="@{/login/jquery.min.js}" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div th:if="${uploadStatus}" style="color: red;" th:text="{uploadStatus}">上传成功</div>

<form th:action="@{uploadFile}" method="post" enctype="multipart/form-data">
    上传文件:&nbsp;&nbsp;<input type="button" value="添加文件" onclick="add()">
    <div id="file" style="margin-top: 10px;" th:value="文件上传区域"></div>
    <input type="submit" id="submit" value="上传" style="display: none;margin-top: 10px;"/>
</form>

<script type="text/javascript">
    function add(){
        var innerdiv = "<div>";
        innerdiv += "<input type='file' name='fileUpload' required='required'>"+
            "<input type='button' value='删除' οnclick='remove(this)'>";
        innerdiv +="</div>";
        $('#file').append(innerdiv);
        $("#submit").css("display","block");
    }
    function remove(obj){
        $(obj).parent.remove();
        if($("#file div").length==0){
            $("submit").css("display","none");
        }
    }
</script>

</body>
</html>

编写java代码

package com.example.springbootstudentsystem;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.UUID;


@Controller
public class test {


    @GetMapping("toUpload")
    public String test(){
        return "test";
    }

    @PostMapping("/uploadFile")
    public String uploadFile(MultipartFile[] fileUpload,Model model){
        //默认文件上传成功,并返回状态信息
        model.addAttribute("uploadStatus","上传成功");
        for(MultipartFile file:fileUpload){
            //获取文件名以及后缀名
            String fileName = file.getOriginalFilename();
            //指定上传文件本地储存目录,不存在则需要提前创建
            String dirPath = "D://program/Springbootstudentsystem/src/main/resources/static/";
            File filePath = new File(dirPath);
            if(!filePath.exists()){
                filePath.mkdir();
            }
            try {
                file.transferTo(new File(dirPath+fileName));
            }catch (Exception e){
                e.printStackTrace();
                model.addAttribute("uploadStatus","上传失败"+e.getMessage());
            }
        }
        return "test";
    }
}

在这里插入图片描述
在这里插入图片描述

静态资源文件下载:

添加依赖:

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>

编写下载页面:

<!DOCTYPE html>
<html lang="zn" xmlns="http://www.thymeleaf.org">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>文件下载</title>
</head>
<body>
<div style="margin-bottom: 10px;">文件下载列表</div>
<table>
	<tr><td>bloglogo.jpg</td>
		<td><a th:href="@{/download(filename='1.jpg')}">下载文件</a></td></tr>

	<tr>
		<td>Springboot应用级开发教程</td>
		<td><a th:href="@{/download(filename='test.txt')}">下载文件</a></td>
	</tr>

</table>
</body>
</html>


编写下载的Controller,

@GetMapping("/toDonwload")
    public String toDownload(){
        return "download";
    }

    @GetMapping("/download")
    public ResponseEntity<byte []> fileDownload(String filename){
        //指定要下载的文件根路径
        String dirPath = "D://program/Springbootstudentsystem/src/main/resources/static/";
        //创建该文件对象,filename就是传递过来的参数
        File file = new File(dirPath+File.separator+filename);
        //设置响应头
        HttpHeaders headers = new HttpHeaders();
        //通知浏览器以下载方式打开
        headers.setContentDispositionFormData("attachment",filename);
        //定义以流的形式下载返回文件数据
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        try{
            return new ResponseEntity<>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

        }catch (Exception e){
            e.printStackTrace();
            return new ResponseEntity<byte[]>(e.getMessage().getBytes(),HttpStatus.EXPECTATION_FAILED);
        }

    }

效果图:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值