SpringBoot實現(xiàn)文件上傳跟刪除文件

介紹

文件上傳是后臺必不可少的技能,提供給前臺圖片上傳最為常見
今天我們來學(xué)習(xí)一下圖片上傳

開始代碼

圖片上傳比較簡單,首先們寫一個方法提供給前臺調(diào)用

創(chuàng)建公共返回類BaseResult

@Data
public class BaseResult {
    private boolean success;
    private String msg;
    private Object data;
}

創(chuàng)建ImgsController

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import sun.tools.jstat.Token;
import zhongmeiutilsapi.td0f7.cn.base.BaseResult;
import zhongmeiutilsapi.td0f7.cn.entrty.Imgs;
import zhongmeiutilsapi.td0f7.cn.entrty.User;
import zhongmeiutilsapi.td0f7.cn.mapper.ImgsMapper;
import zhongmeiutilsapi.td0f7.cn.mapper.UserMapper;
import zhongmeiutilsapi.td0f7.cn.token.TokenUtil;
import zhongmeiutilsapi.td0f7.cn.token.UserLoginToken;
import zhongmeiutilsapi.td0f7.cn.utils.FileUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("Imgs")
public class ImgsController {

    @PostMapping//文件參數(shù)必須用MultipartFile接收
    public BaseResult upload(@RequestParam(value = "file") MultipartFile file) {
        BaseResult data = new BaseResult();
        try {
        //文件保存的路徑
            String path = "/www/wwwroot/app.td0f7.cn/images";

            String result = FileUtils.upload(file, path, new File(file.getOriginalFilename()).getPath());
        //通過工具類保存文件
            data.setSuccess(true);
            data.setMsg("成功上傳!");
            data.setData(result);//result是保存文件后返回的路徑
        } catch (Exception e) {
            e.printStackTrace();
            data.setMsg(e.getMessage());
        //如果發(fā)生異常,則代表文件保存出錯了Success默認是false,所以不用修改
        }
        return data;
    }

    @PutMapping
    public BaseResult delete(@RequestParam(value = "id") int id) {
        BaseResult result = new BaseResult();
        Imgs imgs = mapper.findById(id);
        result.setSuccess(FileUtils.deleteFile(imgs.getPath()));
        if (result.isSuccess()) mapper.delete(id);//刪除工具類返回一個bool得值,直接給Success字段
        result.setMsg(result.isSuccess() ? "刪除成功!" : "刪除失敗!");//如果Success=true刪除成功,反之刪除失敗
        return result;
    }
}

創(chuàng)建文件上傳工具類

import org.springframework.web.multipart.MultipartFile;

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

public class FileUtils {
    public static String upload(MultipartFile file, String path, String fileName) throws Exception {
        // 生成新的文件名
        String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf("."));
        File dest = new File(realPath);
        // 判斷文件父目錄是否存在
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdir();
        }
        // 保存文件
        file.transferTo(dest);
        return realPath;
    }

    public static boolean deleteFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            return file.delete();
        }
        return false;
    }
}

這樣圖片上傳就完成啦

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容