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 "保存成功";
        }


}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot中,可以使用Spring Data JPA和Hibernate实现将文件存储到数据库中。以下是实现文件上传并将其保存到数据库中的步骤: 1. 创建一个实体类,包含一个字段用于存储文件内容(一般使用byte[]类型),以及其他必要的字段。 ```java @Entity public class FileEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String fileName; private String fileType; @Lob private byte[] data; // getters and setters } ``` 2. 创建一个控制器,用于处理文件上传请求。在控制器中,使用Spring的MultipartFile类来接收上传的文件,并将其保存到数据库中。 ```java @RestController @RequestMapping("/api/files") public class FileController { @Autowired private FileRepository fileRepository; @PostMapping("/upload") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) { try { // Create a new FileEntity object and set its fields FileEntity fileEntity = new FileEntity(); fileEntity.setFileName(file.getOriginalFilename()); fileEntity.setFileType(file.getContentType()); fileEntity.setData(file.getBytes()); // Save the file to the database fileRepository.save(fileEntity); return new ResponseEntity<>("File uploaded successfully", HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity<>("Failed to upload file", HttpStatus.INTERNAL_SERVER_ERROR); } } } ``` 3. 创建一个Spring Data JPA存储库,用于与数据库交互。在存储库中,定义一个方法用于保存FileEntity对象。 ```java @Repository public interface FileRepository extends JpaRepository<FileEntity, Long> { // Define any additional methods here } ``` 4. 在应用程序配置文件中,配置数据库连接信息和JPA属性。例如,如果使用MySQL数据库,可以添加以下属性: ``` spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase spring.datasource.username=myusername spring.datasource.password=mypassword spring.jpa.hibernate.ddl-auto=update ``` 这样,你就可以将上传的文件保存到数据库中了。当需要访问文件时,可以从数据库中检索FileEntity对象,并将其数据字段发送回客户端。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值