SpringBoot的Class目录保存上传文件

SpringBoot的Class目录保存上传文件




package cn.js.Controller;

import org.apache.commons.codec.digest.DigestUtils;
import org.docx4j.openpackaging.exceptions.Docx4JException;
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;

import java.io.*;
import java.net.URL;
import java.util.UUID;

/**
 * @Description:   在 SpringBoot的class文件中创一个保存文件的目录
 * @Author: com.js
 * @CreateTime: 2023-05-22  17:02
 * @Version: 1.0
 * @introduce:
 */

@RequestMapping("/filesave")
@RestController
public class FileUpdateTest {

    @PostMapping("/supdate")
    public String savefile(@RequestParam("file") MultipartFile file) throws IOException{



        String filename=file.getOriginalFilename();
        // 获取资源路径
        URL resourceUrl = getClass().getResource("/");

// 构建文件保存目录
        File directory = new File(resourceUrl.getFile() + "/saved_files");
        directory.mkdirs();

        //生成uuid
        UUID uuid = UUID.randomUUID();
        String uuidStr = uuid.toString().replace("-", "");
        String hash = DigestUtils.md5Hex(uuidStr);
        String uid= hash.substring(0, 8);


// 构建要保存的文件
        String path = directory.getPath();
        System.out.println("文件路径:"+path);
        File fileToSave = new File(directory.getPath()  +File.separator + uid+filename);

// 将内容写入文件


        FileOutputStream fos = new FileOutputStream(fileToSave);

        FileInputStream fis =(FileInputStream) file.getInputStream();

        byte[] buf = new byte[1024];
        int len;

        while ((len = fis.read(buf)) != -1) {
            fos.write(buf, 0, len);
        }
        fis.close();

        fos.close();

        File feile=new File(path+File.separator + uid+filename);
        //删除文件
        feile.delete();





          return "保存成功";
        }


}

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)