springboot上传文件到指定目录及配置

本文详细介绍了如何在SpringBoot 2.0中配置文件上传的最大大小限制,包括使用application.properties和application.yml两种方式,并提供了一个简单的文件上传控制器代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在springboot2.0上面配置上传文件大小

1、application.properties

spring.servlet.multipart.max-file-size=1024MB
spring.servlet.multipart.max-request-size=1024MB

2、application.yml

spring:
    servlet:
        multipart:
           enabled: true
           max-file-size: 1024MB
           max-request-size: 1024MB

springboot简单代码:

package com.clkj.hospital.modules.oos.controller;

import com.clkj.hospital.common.bean.Resp;
import lombok.extern.slf4j.Slf4j;
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.File;
import java.io.IOException;

/**
 * @Author: xf
 * @Date: 2019/6/26 17:57
 * @Version 1.0
 */
@Slf4j
@RestController
@RequestMapping("/test/")
public class UploadController {

    @RequestMapping("/upload")
    public Resp upload(@RequestParam(value = "file", required = false) MultipartFile file) {
        if (file.isEmpty()) return Resp.fail("上传失败,请选择文件");
        String filename = file.getOriginalFilename();
        String filePath = "E:\\";
        File dest = new File(filePath + filename);
        try {
            file.transferTo(dest);
            log.info("上传成功");
            return Resp.success("upload success");
        } catch (IOException e) {
            e.printStackTrace();
            return Resp.fail("upload failed");
        }
    }
    

}

 

### Spring Boot 文件上传至阿里云 OSS 的配置与实现 #### 配置依赖项 为了能够使用 Spring Boot 将文件上传到阿里云对象存储服务 (OSS),需要引入相应的 Maven 或 Gradle 依赖。 对于 Maven 用户,在 `pom.xml` 中添加如下依赖: ```xml <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>3.10.2</version> </dependency> ``` 对于 Gradle 用户,则应在 build.gradle 添加: ```groovy implementation 'com.aliyun.oss:aliyun-sdk-oss:3.10.2' ``` #### 应用程序属性设置 在应用程序的配置文件 application.properties 或者 application.yml 中定义连接参数以及目标 Bucket 和访问权限信息: ```yaml spring: cloud: alibaba: oss: endpoint: ${your-endpoint} access-key-id: ${your-access-key-id} secret-access-key: ${your-secret-access-key} bucket-name: ${bucket-name} ``` 以上配置用于初始化客户端并建立安全认证[^1]。 #### 创建 OSS 客户端工具类 创建一个名为 OssClientUtil.java 工具类来封装常见的操作方法,比如获取/删除对象、列举桶内资源等。这里主要关注于文件上传功能: ```java import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; public class OssClientUtil { private final String endpoint; private final String accessKeyId; private final String accessKeySecret; private final String bucketName; public OssClientUtil(String endpoint, String accessKeyId, String accessKeySecret, String bucketName){ this.endpoint = endpoint; this.accessKeyId = accessKeyId; this.accessKeySecret = accessKeySecret; this.bucketName = bucketName; } /** * Uploads a file to the specified directory within an AliCloud OSS bucket. */ public void uploadFileToDirectory(MultipartFile multipartFile, String targetDir) throws IOException { try (InputStream inputStream = multipartFile.getInputStream()) { // Initialize client with credentials and region information try(OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret)) { // Construct object key by combining directory path and original filename String fileName = multipartFile.getOriginalFilename(); String objectKey = targetDir.endsWith("/") ? targetDir + fileName : targetDir + "/" + fileName; // Put Object into specific folder inside the bucket ossClient.putObject(bucketName, objectKey, inputStream); System.out.println("Upload successful."); } } catch (Exception e) { throw new RuntimeException(e.getMessage(), e.getCause()); } } } ``` 此代码片段展示了如何通过 Java API 实现向特定路径下保存文件的功能[^2]。 #### 控制器层处理 HTTP 请求 最后一步是在控制器 Controller 层编写 RESTful 接口接收前端传来的文件数据,并调用上述工具类完成实际业务逻辑: ```java @RestController @RequestMapping("/api/files") public class FileController { @Autowired private OssClientUtil ossClientUtil; @PostMapping("/upload/{dir}") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file, @PathVariable String dir) { if (!file.isEmpty()) { try { ossClientUtil.uploadFileToDirectory(file, "uploads/" + dir); // 自动追加 uploads 前缀作为根目录 return ResponseEntity.ok("Successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException ex) { return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(ex.toString()); } } else { return ResponseEntity.badRequest().body("Failed to upload empty file"); } } } ``` 这段代码实现了 POST /api/files/upload/{dir} 路径下的接口,允许用户提交表单中的文件字段并通过 URL 参数指定要存入的目标子目录名称[^3]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值