SpringBoot文件上传与下载

本文介绍了一个使用SpringBoot实现的文件上传功能,包括代码实现、文件大小限制的设置、静态资源访问配置等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

上传文件代码

package com.example.demo.controller;

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

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

@RestController
@RequestMapping(path = "/file")
public class FileController {

    /*上传文件的路径*/
    static final String PATH = "D:\\picture";

    @RequestMapping(path = "/fileUpload")
//    public String fileUpload(MultipartFile[] file) {
    public String fileUpload(MultipartFile file) {

        String newFileName = "";

        /*生成UUID*/
        String uuid = UUID.randomUUID().toString();

        /*获取上传文件的全名*/
        String fileName = file.getOriginalFilename();

        /*截取文件后缀名*/
        String suffix = fileName.substring(fileName.lastIndexOf("."));

        /*根据path路径创建file对象*/
        File realPathFolder = new File(PATH);

        /*判断此路径下的目录是否存在,不存在就创建*/
        if (!realPathFolder.exists()) {
            realPathFolder.mkdirs();
        }

        /*生成新的文件名称*/
        newFileName = uuid + suffix;

        /*根据路径和新的文件名创建file对象*/
        File newFile = new File(realPathFolder, newFileName);

        /*上传图片到指定路径*/
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            System.out.println("上传文件失败!" + e);
        }
        /*返回访问路径*/
        return "localhost:8080/files/" + newFileName;
    }
}

设置文件大小限制

spring:
  servlet:
    multipart:
      max-request-size: 100MB
      max-file-size: 10MB
#     maxFileSize 是单个文件大小
#     maxRequestSize是设置总上传的数据大小

配置静态资源访问

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
                /*访问时的虚拟路径*/
                .addResourceHandler("/files/**")
                /*资源真实路径*/
                .addResourceLocations("file:D:\\picture\\");
    }
}

测试

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

不畏浮云遮望眼,只缘身在最高层。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值