基于springboot的文件上传

Spring Boot文件上传示例--前后端不分离

大致步骤总览

1.创建upload模块项目
2.添加web,thymeleaf依赖
3.配置上传属性application.properties,指定上传文件大小限制等
4.编写Controller控制器,通过kava.nio实现文件的上传
5.控制器配置好thymeleaf的页面跳转及信息显示
6.运行项目,上传文件,观察结果

基本步骤:

  • 创建模块的时候注意添加web和thymeleaf依赖

    image
    image
  • 配置上传属性application.properties

    image
  • 编写控制器代码

package com.springboot.upload.controller;

import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * 上传文件控制器
 * 直接上传到服务器
 * @author Wuyou
 * 2019.3.25
 */
@Controller
public class UploadController {
    //指定一个临时路径作为上传目录
//    private static String UPLOAD_FOLDER = "E:/temp/";

    //遇到http://localhost:8080,则跳转到upload.html页面
    SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
    @GetMapping("/")
    public String index(){
        return  "upload";
    }

    @PostMapping("/upload")
    public String fileUpload(@RequestParam("file")MultipartFile srcFile, RedirectAttributes redirectAttributes){
        //前端没有选择文件,srcFile为空
        if (srcFile.isEmpty()){
            redirectAttributes.addFlashAttribute("message","请选择一个文件");
            return "redirect:upload_status";
        }
        //选择了文件,开始进行上传操作
        try {
            //构建上传目标路径,
            File destFile=new File
                    (ResourceUtils.getURL("classpath:").getPath());
            if(!destFile.exists()){
                destFile=new File("");
            }
            //出处目标文件的绝对路径
            System.out.println("file path"+destFile.getAbsolutePath());
            File upload=new File(destFile.getAbsolutePath(),dateformat.format(new Date())+"/");

            String fileName= srcFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            fileName= UUID.randomUUID() +suffixName;
            //若目标文件夹不存在,则创建一个
            if(!upload.exists()){
                upload.mkdir();
            }
            System.out.println("完整的上传路径:"+upload.getAbsolutePath()+"/"+fileName);

            //根据srcFile的大小,准备一个字节数组
            byte[] bytes = srcFile.getBytes();
            //拼接上传路径
            Path path = Paths.get(upload.getAbsolutePath()+"/"+fileName);
            //最重要的一步,将源文件写入目标地址
            Files.write(path , bytes);
            //将文件上传成功的信息写入message
            redirectAttributes.addFlashAttribute("message","文件上传成功!,文件已重命名为:"+fileName);
        }catch (IOException e){
            e.printStackTrace();
        }
        return "redirect:upload_status";
    }

 //匹配upload_status页面
    @GetMapping("/upload_status")
    public String uploadStatusPage(){
        return "upload_status";
    }
}

  • upload.html和upload_status.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Spring Boot文件上传页面</title>
</head>
<body>
<form method="post" action="/upload" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">

</form>
</body>
</html>

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>文件上传状态显示</title>
</head>
<body>
<h2>Spring Boot的文件上传状态</h2>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

  • 运行结果

    • 首先运行application类,启动服务器

      image
      image
    • 在浏览器地址栏输入localhost:8080

      image
      image
      image
      image
  • 在target目录下可以找到该图片

    image

    打包后运行

  • 打包

    image
  • 将打包后的文件名修改简单一些

    image
    image

    注意:要先停止idea的服务器

  • 重复之前的浏览器上传操作

    image
    image
    image
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 上传方式: 直接上传到应用服务器 上传到css(阿里云、七牛云) 前端将图片转成Base64编码上传 http:/...
    啊肉怪阅读 683评论 0 0
  • 三种上传方式 直接上传到应用服务器 上传到oss(内容存储在服务器)如 阿里云 七牛云 前端将图片转成Base64...
    youi_e050阅读 618评论 1 4
  • 文件上传的三种方法 直接上传到应用服务器 上传到OSS(阿里云 七牛云) 前端将图片转成Base64编码上传 Sp...
    老婆日向雏田阅读 231评论 0 0
  • 过去的东西,现在回想起来,也是挺有味道的。看别人的态度我感觉我是,你挺好的,我差不多吧。小时候就是见不得别人好。现...
    可爱的三姑阅读 160评论 0 0
  • 编写middleware.py 文件中的类 为每个spider配置私有配置
    还是那个没头脑阅读 193评论 0 0