0x04 一个关于文件上传的简易项目

发布时间 2023-08-11 20:51:44作者: Icfh

本小节将介绍SpringBoot中的静态资源访问配置,文件上传以及拦截器。

实现一个文件上传和查看文件的简易SpringBoot Demo!

静态资源访问配置

主要是怎么做好文件和web访问下的映射关系

比如,在我的src/main/resources路径下,有如下层级关系

image-20230808155206801

配置如下:

在前端请求时,应该请求/images/路由,映射访问到的路由为resources/upload/

spring.mvc.static-path-pattern=/images/**
#spring.web.resources.static-locations=classpath:/static/
spring.web.resources.static-locations=classpath:/upload/

文件上传小项目

这里放出文件上传的相应控制器

package com.example.icfh_springboot1.controller;

import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileController {

    // 文件上传的目录
    private static final String UPLOADED_FOLDER = System.getProperty("user.dir")+"/upload/";


    @PostMapping("/upload")
    public String up(String nickname, MultipartFile photo, HttpServletRequest request) throws IOException{
        System.out.println(nickname);
        // 获取照片的原始名称
        System.out.println(photo.getOriginalFilename());
        // 获取文件类型
        System.out.println(photo.getContentType());

        // 部署到不同的机器上,绝对路径会不同
        String path = request.getServletContext().getRealPath("/upload/");
        System.out.println(path);
        saveFile(photo, path);
        return "Upload Success!";
    }

    public void saveFile(MultipartFile photo, String path) throws IOException{
        // 创建路径
        File upDir = new File(path);			
        if(!upDir.exists()){		// 路径不存在时则创建
            upDir.mkdir();
        }
        // 在该路径下创建文件
        File file = new File(path+photo.getOriginalFilename());
        // 将文件二进制内容写入file
        photo.transferTo(file);
    }

}

考虑到要上传的enctype类型为multipart/form-data,此处采用MultipartFile接收上传文件。

大致的逻辑是通过MultipartFile来接受文件,然后可以通过该句柄来获取文件的诸多属性,包括文件名、文件大小...

接收上传的文件后得将文件进行落地处理:savaFile

saveFile的逻辑大概是:首先判断路径是否存在,不存在则进行目录创建,然后使用transferTo将文件内容写入File对象里

拦截器

image-20230808155041364