欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接的示例代碼

 更新時(shí)間:2024年11月12日 09:55:39   作者:mr_cmx  
文件上傳,當(dāng)我們選擇了某一個圖片文件之后,這個文件就會上傳到服務(wù)器,從而完成文件上傳的操作,是指將本地圖片、視頻、音頻等文件上傳到服務(wù)器,供其他用戶瀏覽或下載的過程,本文給大家介紹了SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接,需要的朋友可以參考下

檢查依賴

確保pom.xml包含了Spring Boot Web的依賴

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

創(chuàng)建Controller

創(chuàng)建公用上傳文件控制器

package com.example.ruijisboot.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;

import javax.servlet.ServletContext;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileUploadController {

    @Autowired
    private ServletContext servletContext;

    @PostMapping("/upload")
    public R handleFileUpload(MultipartFile file) {
        System.out.println(file);
        if (file.isEmpty()) {
//            return "Please select a file to upload.";
            return R.error("Please select a file to upload.");
        }
        try {
            // 構(gòu)建上傳目錄的路徑
            String uploadDir = servletContext.getRealPath("/upload/test/");
            // 確保目錄存在
            File dirPath = new File(uploadDir);
            if (!dirPath.exists()) {
                dirPath.mkdirs();
            }
            // 構(gòu)建上傳文件的完整路徑
            Path path = Paths.get(uploadDir).resolve(file.getOriginalFilename());
            System.out.println(path);
            // 保存文件
            Files.write(path, file.getBytes());
            // 構(gòu)建文件在Web應(yīng)用中的URL
            String fileUrl = ServletUriComponentsBuilder.fromCurrentContextPath()
                    .path("/upload/test/")
                    .path(file.getOriginalFilename())
                    .toUriString();
//            return "File uploaded successfully! You can download it from: " + fileUrl;
            return R.success(fileUrl,"成功");
        } catch (IOException e) {
            e.printStackTrace();
//            return "File upload failed!";
            return R.error("File upload failed!");
        }
    }
}

這里R為我本地封裝的統(tǒng)一返回格式的類

配置屬性

在application.properties或application.yml中,你可以配置一些與文件上傳相關(guān)的屬性,比如文件大小限制等。

# application.properties 示例  
spring.servlet.multipart.max-file-size=128KB  
spring.servlet.multipart.max-request-size=10MB

驗(yàn)證

請求 /upload 路徑

文件會默認(rèn)放在系統(tǒng)的臨時(shí)文件目錄

到此這篇關(guān)于SpringBoot實(shí)現(xiàn)文件上傳并返回url鏈接的示例代碼的文章就介紹到這了,更多相關(guān)SpringBoot文件上傳并返回url內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論