Spring Boot web开发(三) 文件上传与下载

目录

1. 文件下载

1.1 前端页面

1.2 Controller层

2. 文件上传

2.1 前端页面

2.2 Controller层

2.3 上传成功的文件如何访问?


在实际的开发项目中,对于文件的上传和下载处理是必不可少的的一部分,比如某某某网站的个人中心,我想要更换一个头像,这时候就涉及到文件上传了。又比如某某教育网站,需要导出学生成绩表,这个时候文件下载功能也就必须要去做了,这里也就简单的举了两个简单的例子,来说明文件上传和下载在实际开发过程中应用在什么地方。

1. 文件下载

1.1 前端页面

就在Spring Boot web开发(二) 页面国际化和登录拦截器的项目基础上面加,首先删除原来的suss.html页面的内容,添加一个下载按钮,并且绑定一个点击函数,具体操作如下:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传与下载</title>
    <style>
    .btn{
        width: 109px;
        height: 38px;
        border-width:0px;
        vertical-align:middle;
        box-shadow:1px 2px 2px #CCCCCC;
        border-radius:2px;
        background-color: #1bbaff;
        cursor:pointer;
    }
    .btn:hover{
        background-color: #0e9fff;
    }
</style>
</head>
<body style="padding: 10px">

<div style="margin-top: 10px;">
    <button class="btn" onclick="downloadfile()">下载文件</button>
</div>
<script>
    function downloadfile() {
        location.href="/download"
    }
</script>
</body>
</html>

页面效果如下:

1.2 Controller层

添加一个下载文件的方法:

    @RequestMapping("/download")
    public void download(HttpServletResponse response) throws IOException{
        response.setContentType("text/html;charset=utf-8");
        //要下载文件的路径和名称
        FileInputStream fis = new FileInputStream("E:\\迅雷下载\\商务严谨Word简历模板(IT类).doc");
        response.reset();
        response.addHeader("Content-Type","application/octet-stream");
        response.addHeader("Content-Disposition", "attatchment;fileName="+new String("商务严谨Word简历模板(IT类).doc".getBytes("utf-8"),"ISO-8859-1"));//添加响应头部
        OutputStream os = response.getOutputStream();
        int b = fis.read();
        while(b!=-1) {
            os.write(b);
            b = fis.read();
        }
        fis.close();
        os.flush();//清空缓冲区
    }

启动服务器,访问localhost:8081,登录后直接点击下载:就会出现下载效果。

2. 文件上传

2.1 前端页面

修改suss.html
 

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传与下载</title>
    <style>
    /*样式1*/
    .a-upload {
        padding: 4px 10px;
        height: 20px;
        line-height: 20px;
        position: relative;
        cursor: pointer;
        color: #888;
        background: #fafafa;
        border: 1px solid #ddd;
        border-radius: 4px;
        overflow: hidden;
        display: inline-block;
        *display: inline;
        *zoom: 1
    }
    .a-upload  input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
        filter: alpha(opacity=0);
        cursor: pointer
    }
    .a-upload:hover {
        color: #444;
        background: #eee;
        border-color: #ccc;
        text-decoration: none
    }
    /*样式2*/
    .file {
        position: relative;
        display: inline-block;
        background: #D0EEFF;
        border: 1px solid #99D3F5;
        border-radius: 4px;
        padding: 4px 12px;
        overflow: hidden;
        color: #1E88C7;
        text-decoration: none;
        cursor:pointer;
        text-indent: 0;
        line-height: 20px;
    }
    .file input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
    }
    .file:hover {
        background: #AADFFD;
        border-color: #78C3F3;
        color: #004974;
        text-decoration: none;
    }
    .btn{
        width: 109px;
        height: 38px;
        border-width:0px;
        vertical-align:middle;
        box-shadow:1px 2px 2px #CCCCCC;
        border-radius:2px;
        background-color: #1bbaff;
        cursor:pointer;
    }
    .btn:hover{
        background-color: #0e9fff;
    }
</style>
</head>
<body style="padding: 10px">
<div th:if="${msg1} != null">
    <div th:text="${msg1}"></div>
</div>
<form action="/fileup" method="post" enctype="multipart/form-data">
    <div>
        <label for="username">用户名:</label>
        <input type="text" id="username" name="username">
    </div>
    <div style="margin-top: 10px;">
        <a href="javascript:;" class="a-upload">
            <input type="file" name="filename">选择文件:文件一
        </a>
    </div>
    <div>
        <a href="javascript:;" class="file">选择文件:文件二
            <input type="file" name="filename">
        </a>
    </div>
    <div>
        <input type="submit" value="上传" class="btn">
    </div>
</form>
<div style="margin-top: 10px;">
    <button class="btn" onclick="downloadfile()">下载文件</button>
</div>
<script>
    function downloadfile() {
        location.href="/download"
    }
</script>
</body>
</html>

2.2 Controller层

添加文件上传的函数

    @RequestMapping("/fileup")
    public String fileup(HttpServletRequest request,String username,Model model) {
        //获取全部文件
        logger.info("username:"+username);
        List<MultipartFile> files = ((MultipartHttpServletRequest) request).getFiles("filename");
        // 商品图片本地保存路径
        String uploadPath = "D://SpringBootUpload";
        File file = new File(uploadPath);
        // 存储路径不存在则创建文件夹
        if (!file.exists()) {
            file.mkdirs();
        }
        for (MultipartFile f : files) {
            if (f.isEmpty()) {
                continue;
            }
            File target = new File(uploadPath + file.separator + f.getOriginalFilename());
            try {
                f.transferTo(target);
            } catch (IllegalStateException | IOException e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("msg1","上传成功!");
        return "suss";
    }

启动服务器,随便上传一点文件:

如果遇到以下错误,在application.properties添加一句配置,来说明上传文件的最大大小,如果不指定默认是1M,文件大小超过1M就会出现以下错误:

application.properties添加一句配置,也可以加上单位MB

spring.servlet.multipart.max-file-size=10485760

再次上传就可以了。

2.3 上传成功的文件如何访问?

这个时候我们需要在配置文件中添加一个静态路径:

lcbs.imagespath=D:/SpringBootUpload/

然后,在配置类中添加一个方法,将这个路径映射到我们指定的文件夹下面

   @Value("${lcbs.imagespath}")
            private String filePath; //配置文件配置的物理保存地址
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/images1/**").addResourceLocations("file:"+filePath);
                super.addResourceHandlers(registry);
            }

修改myConfig 

package com.chtw.config;

import com.chtw.interceptor.LoginInterceptor;
import com.sun.org.apache.xpath.internal.SourceTree;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author CHTW
 * @date 2019-10-15-9:12
 */
@Configuration
public class myConfig extends WebMvcConfigurerAdapter{
    //将组件添加在容器中

    @Bean
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");
                registry.addViewController("/main.html").setViewName("suss");
                //为了防止数据重复提交,登录成功后我们将页面重定向到main.html这个请求,这里添加一个视图解析器,将mian.html定位到suss.html
            }
            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //super.addInterceptors(registry);
                //静态资源;  *.css , *.js
                //SpringBoot已经做好了静态资源映射
                registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**")
                        .excludePathPatterns("/index.html","/","/css/**","/js/**","/login","/fonts/**","/img/**");
                /*
                 * addPathPatterns设置拦截路径
                 * excludePathPatterns设置不拦截的路径
                 */
            }

            @Value("${lcbs.imagespath}")
            private String filePath; //配置文件配置的物理保存地址
            @Override
            public void addResourceHandlers(ResourceHandlerRegistry registry) {
                registry.addResourceHandler("/images1/**").addResourceLocations("file:"+filePath);
                super.addResourceHandlers(registry);
            }
        };
        return adapter;
    }

}

最后,在前端加一个img标签看看能否访问成功:

启动浏览器,登录后出现以下界面说明成功访问到文件:

本节类容到此结束

本人联系方式2329095893,欢迎各位进行学习讨论

欢迎关注熊熊出没ING公众号,不定时跟新Java、python、信息安全等相关知识哦。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值