SpringBoot文件上传、下载和删除

程序实现

1、POM文件

<properties>
        <java.version>1.8</java.version>
        <swagger.version>2.9.2</swagger.version>
        <swagger-models.version>1.5.22</swagger-models.version>
        <fastjson.version>1.2.76</fastjson.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.9</version>
        </dependency>

        <!-- Swagger 依赖配置 -->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>${swagger.version}</version>
            <exclusions>
                <exclusion>
                    <groupId>io.swagger</groupId>
                    <artifactId>swagger-models</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-models</artifactId>
            <version>${swagger-models.version}</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>${swagger.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

2、application.yml

server:
  port: 8080

spring:
  mvc:
    view:
      prefix: classpath:/templates/
      suffix: .html

  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 100MB
file:
  upload-path: F:/data/
  size: 52428800    # 50*1024*1024,文件大小<50M

3 、FileController

package com.study.fileoption.controller;

import com.study.fileoption.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/file")
@Api("文件操作")
public class FileController {

    @Autowired
    private FileService fileService;

    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public String upload(@RequestParam("file") MultipartFile file) throws Exception {
        fileService.fileUpload(file);
        return "success";
    }

    @PostMapping("/download")
    @ApiOperation("文件下载")
    public String download(@RequestParam("fileName") String fileName, HttpServletResponse response) throws Exception {
        fileService.fileDownload(fileName,response);
        return "success";
    }

    @DeleteMapping("/delete")
    @ApiOperation("文件删除")
    public String delete(@RequestParam("fileName") String fileName) throws Exception {
        fileService.fileDelete(fileName);
        return "success";
    }
    
}

4、FileService

package com.study.fileoption.service;


import lombok.extern.slf4j.Slf4j;
import cn.hutool.core.io.FileUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;

@Service
@Slf4j
public class FileService {

    @Value("${file.upload-path}")
    private  String filePath;

    @Value("${file.size}")
    private  Long fileSize;


    public String fileUpload(MultipartFile file) throws Exception {
        try {
            if (file.isEmpty()) {
                return "文件为空";
            }
            log.info(file.getOriginalFilename());

            // 判断上传文件大小
            if (file.getSize() >fileSize) {
                log.error("上传文件规定小于50MB");
                throw new Exception("上传文件大于50MB");
            }
            // 获取文件名
            String fileName = file.getOriginalFilename();
            log.info("文件名:" + fileName);
            // 获取文件的后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            log.info("文件后缀:" + suffixName);

            // 设置文件存储路径
            String path = filePath + fileName;
            File dest = new File(path);
            // 检测是否存在目录,不存在则创建
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
            }
            // 文件写入
            file.transferTo(dest);
            return "上传成功";
        } catch (Exception e) {
            log.error("上传失败: <{}>",e.getMessage(),e);
        }
        return "上传失败";
    }

    public void fileDownload(String fileName, HttpServletResponse response) throws Exception {
        //1、检查是否存在文件
        File file = new File(filePath + fileName);
        if (!file.exists()) {
            log.error(fileName+" is not exist!");
            throw new Exception("文件不存在");
        }

        //2、下载文件
        try {
            downloadFile(response, file);
        } catch (Exception e) {
            log.error("文件下载异常: <{}>", e.getMessage(), e);
            throw new Exception("文件下载失败");
        }
    }

    public String fileDelete(String fileName) throws Exception {
        File file = new File(filePath+fileName);
        if (!file.exists()) {
            log.error("文件不存在");
            throw new Exception("文件不存在");
        }
        try {
            if(file.delete()){
                return fileName;
            }
        } catch (Exception e) {
            log.error("文件删除异常: <{}>", e.getMessage(), e);
        }
        log.error("文件删除失败");
        throw new Exception("文件删除失败");
    }

    private void downloadFile(HttpServletResponse response, File file) throws Exception {
        if (file.exists()) {
            String filename = file.getName();

            byte[] buffer = new byte[1024];
            //输出流
            try (FileInputStream fis = new FileInputStream(file);
                 BufferedInputStream bis = new BufferedInputStream(fis);
                 OutputStream os = response.getOutputStream();) {
                response.setContentType("application/octet-stream");
                response.setHeader("content-type", "application/octet-stream");
                response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(filename, "utf8"));
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                throw new Exception("文件下载失败");
            }
        }
    }
}

5、SwaggerConfig

package com.study.fileoption.config;



import io.swagger.annotations.ApiOperation;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

@Configuration
@EnableSwagger2
public class SwaggerConfig {


    private Boolean swaggerEnable = true;

    public static String SWAGGER_TITLE="文件操作";
    public static String SWAGGER_VERSION="1.0";
    public final static String SWAGGER_URL="http://127.0.0.1:8080";

    /**
     *
     * 验证的页面http://127.0.0.1:8080/swagger-ui.html
     * @return
     */

    @Bean
    public Docket createRestApi() {

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(swaggerEnable)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(SWAGGER_TITLE)
                .termsOfServiceUrl(SWAGGER_URL)
                .version(SWAGGER_VERSION)
                .build();
    }

}

测试

1、访问 http://localhost:8080/swagger-ui.html
在这里插入图片描述可对上传、下载、删除功能分别测试,均无异常。

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
要在Java Spring Boot中实现文件上传下载功能,可以按照以下步骤进行操作: 1. 首先,在项目的pom.xml文件中添加web依赖,如下所示: ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> ``` 2. 创建一个HTML文件,用于实现文件上传下载的前端页面。 3. 在Spring Boot中,可以通过创建一个Controller来处理文件上传下载的请求。在Controller中,可以使用`@PostMapping`注解来处理文件上传请求,并使用`@GetMapping`注解来处理文件下载请求。在处理文件上传请求时,可以使用`MultipartFile`类型的参数来接收上传的文件。在处理文件下载请求时,可以使用`ResponseEntity`类型的返回值来返回文件给客户端。 4. 在Controller中,可以使用`File`类或`Path`类来处理文件的读取、写入和删除等操作。可以使用`Files`类提供的方法来实现文件的复制、移动和重命名等操作。 5. 在处理文件上传下载时,需要注意安全性和文件大小的限制。可以使用`@RequestParam`注解来限制文件的大小,并使用`@Valid`注解来验证文件的合法性。 通过以上步骤,您就可以在Java Spring Boot中实现文件上传下载功能了。希望以上信息对您有所帮助。\[1\]\[2\]\[3\] #### 引用[.reference_title] - *1* [java SpringBoot文件上传,](https://blog.csdn.net/qingqingyyds/article/details/126614747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* *3* [SpringBoot 如何实现文件上传下载](https://blog.csdn.net/yujun2023/article/details/130905253)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^insert_down1,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zxg45

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值