Springboot 上传和删除本地文件

目录

一、添加配置

二、上传的服务类

三、控制层

四、测试


虽然这个功能对应现在的分布式系统已不用了,但还是做个笔记吧,需要参考OSS云存储的见我 的这篇博客:

Springboot OSS 七牛云 上传、删除、访问图_Dragon Wu的博客-CSDN博客

一、添加配置

file:
  # 本地域名/路径
  root: localhost:8081
  # 文件存储的相对路径
  path: D:/dragonwu/test-file/ # Linux /dragonwu/test-file/
  # 上传文件允许的扩展名
  allowed: png,jpg,jpeg,pdf,bmp

二、上传的服务类

public interface LocalFileStorageService {

    /**
     * 上传文件到本地服务器
     * @param file 文件
     * @return 文件相对路径
     */
    String upload(MultipartFile file) throws RuntimeException;

    /**
     * 删除单个文件
     * @param filePath  删除文件路径名
     * @return 成功true,失败false
     */
    boolean delete(String filePath);

}
package com.dragonwu.service.impl;

import com.dragonwu.service.LocalFileStorageService;
import com.dragonwu.util.DateUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

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

/**
 * @author Dragon Wu
 * @since 2022-10-16 16:58
 **/
@Service
public class LocalFileStorageServiceImpl implements LocalFileStorageService {

    @Value("${file.root}")
    private String root;    //域名/路径
    @Value("${file.path}")
    private String path;       // 存储路径
    @Value("${file.allowed}")
    private String[] allowed; //图片允许的扩展名


    @Override
    public String upload(MultipartFile file) throws RuntimeException {
        //获取原始文件名
        String originalFileName = Objects.requireNonNull(file.getOriginalFilename());
        //判断文件是否允许上传
        if (!isFileAllowed(originalFileName)) throw new IllegalArgumentException();
        //生成文件名
        String fileName = getRandomImgName(originalFileName);

        //创建文件
        File pathDir = new File(path + DateUtils.getTodayDate());
        if (!pathDir.exists()) {
            pathDir.mkdirs();
        }
        String key = path + DateUtils.getTodayDate() + "/" + fileName;
        File dest = new File(key);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("上传失败");
        }
        return key;
    }

    @Override
    public boolean delete(String filePath){
        boolean flag = false;
        //根据路径创建文件对象
        File file = new File(filePath);
        //路径是个文件且不为空时删除文件
        if(file.isFile() && file.exists()){
            flag = file.delete();
        }
        //删除失败时,返回false
        return flag;
    }

    /**
     * 生成唯一图片名称
     *
     * @param fileName 原文件名
     * @return 云服务器fileName
     */
    private static String getRandomImgName(String fileName) throws IllegalArgumentException {
        int index = fileName.lastIndexOf(".");

        if (fileName.isEmpty() || index == -1) {
            throw new IllegalArgumentException();
        }
        // 获取文件后缀
        String suffix = fileName.substring(index).toLowerCase();
        // 生成UUID
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 拼接新的名称
        return uuid + suffix;
    }

    /**
     * 判断文件是否被允许上传
     *
     * @param fileName 文件名
     * @return 允许true, 否则false
     */
    private boolean isFileAllowed(String fileName) {
        // 获取后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        for (String allow : allowed) {
            if (allow.equals(suffixName)) {
                return true;
            }
        }
        return false;
    }
}

三、控制层

package com.dragonwu.controller;

import com.dragonwu.service.LocalFileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author Dragon Wu
 * @since 2022-10-15 17:09
 **/
@RestController
@RequestMapping("/file")
public class FileController {

    @Autowired
    private LocalFileStorageService localFileStorageService;

    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) {
        //上传文件到七牛云服务器
        //把图片放到距离图片最近的服务器上,降低我们自身服务器的带宽消耗
        try {
            return localFileStorageService.upload(file);
        } catch (RuntimeException e) {
            return e.getMessage();
        }
    }

    @DeleteMapping("/delete")
    public String delete(@RequestParam String key) {
        try {
            return localFileStorageService.delete(key)?"文件已删除":"删除失败";
        } catch (RuntimeException e) {
            return e.getMessage();
        }
    }
}

四、测试

上传到对应路径:

 文件删除:

 

文件删除成功! 

  • 6
    点赞
  • 19
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
SpringBoot中,可以通过整合阿里云OSS来实现文件上传、下载、删除等操作。要删除文件,首先需要获取到要删除文件在OSS上的路径。然后,使用阿里云OSS的Java SDK提供的API来进行删除操作。具体步骤如下: 1. 首先,确保已经在pom.xml文件中添加了阿里云OSS的依赖。 2. 在配置文件中配置阿里云OSS的相关信息,包括accessKeyId、accessKeySecret、endpoint等。 3. 在代码中引入阿里云OSS的相关类和方法。 4. 创建一个OSSClient对象,通过accessKeyId和accessKeySecret进行身份验证,并指定endpoint。 5. 调用OSSClient的deleteObject方法,传入存储空间(Bucket)名称和要删除文件在OSS上的路径,即可删除文件。 示例代码如下: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; public class OSSUtils { private static String endpoint = "<your_endpoint>"; private static String accessKeyId = "<your_accessKeyId>"; private static String accessKeySecret = "<your_accessKeySecret>"; private static String bucketName = "<your_bucketName>"; public static void deleteFile(String objectName) { OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); ossClient.deleteObject(bucketName, objectName); ossClient.shutdown(); } } ``` 其中,`objectName`是要删除文件在OSS上的路径。 通过调用`deleteFile`方法,即可删除指定路径下的文件。 请注意,删除操作是不可逆的,请确保在删除文件之前进行适当的验证和确认。 参考资料: SpringBoot项目实现日志打印SQL明细(包括SQL语句和参数)几种方式 虽然这个功能对应现在的分布式系统已不用了,但还是做个笔记吧,需要参考OSS云存储的见我 的这篇博客: 另外OSS还有专门的oss-browser 下载链接: https://help.aliyun.com/document_detail/209974.html 一、 基本概念 1、存储空间(Bucket)<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [SpringBoot整合阿里云OSS,支持文件上传、下载、删除、加签等操作](https://blog.csdn.net/weixin_33005117/article/details/125206220)[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^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [Springboot 上传删除本地文件](https://blog.csdn.net/qq_50909707/article/details/127351663)[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^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值