Springboot文件上传

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
        <form action="http://localhost:8080/fileUpload" method="post" enctype="multipart/form-data">
            姓名<input type="text" name="name"></input><br>
            头像<input type="file" name="images"><br>
            <input type="submit" value="提交">
        </form>
</body>
</html>

后端代码

controller层:需要用MultipartFile类接收文件,file方法执行过程中会产生两个临时文件,分别对应name、images的值。
注意:参数名需要与前端的name属性相对应。

MultipartFile API:
byte[] getBytes() throws IOException; 获取文件内容的字节数组
long getSize(); 获取文件大小
InputStream getInputStream() throws IOException; 获取文件字符输入流
void transferTo(File dest) throws IOException, IllegalStateException; 保存文件

@RestController
@Slf4j
public class HelloController {
    @PostMapping("/fileUpload")
    public String file(String name , MultipartFile images) throws IOException {

        String fileName=images.getOriginalFilename();
        String last=fileName.substring(fileName.lastIndexOf("."));//获取文件扩展名
        String uuid= UUID.randomUUID().toString();//获取唯一标识符,避免重复
        File file = new File("E:/" + uuid+last);
        log.info("生成的文件名 {}",file.getName());
        images.transferTo(file);//保存文件

        return "ok";
    }
}

修改文件上传最大限制

文件上传限制默认为1M,可以通过application.properties文件进行配置

#单个文件最大为10MB
spring.servlet.multipart.max-file-size=10MB
#一次上传的多个文件总大小不超过100MB
spring.servlet.multipart.max-request-size=100MB

阿里云OSS对象存储服务(Object Storage Service)

可以将上传的文件保存到阿里云云存储上。
使用步骤:1.注册/登录阿里云官网 2.申请阿里云OSS 3.创建Bucket 4.点击右上角头像扩展创建AccessKey(密钥)5.根据SDK完成上传操作。
SDK地址:https://oss.console.aliyun.com/sdk

导入阿里云OSS依赖
<dependency>
    <groupId>com.aliyun.oss</groupId>
    <artifactId>aliyun-sdk-oss</artifactId>
    <version>3.15.1</version>
</dependency>

<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.3.1</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>
<!-- no more than 2.3.3-->
<dependency>
    <groupId>org.glassfish.jaxb</groupId>
    <artifactId>jaxb-runtime</artifactId>
    <version>2.3.3</version>
</dependency>
上传文件demo
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import java.io.ByteArrayInputStream;

public class Demo {

    public static void main(String[] args) throws Exception {
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 从环境变量中获取访问凭证。运行本代码示例之前,请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = "exampledir/exampleobject.txt";

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);

        try {
            String content = "Hello OSS";
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content.getBytes()));
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}

整合到web项目中

1.引入依赖(略)
2.将配置写入application.properties中

aliyun.oss.endpoint=https://oss-cn-nanjing.aliyuncs.com
aliyun.oss.bucketName=yihengye-test

3.建立工具类AliossUtils,通过@Value/@ConfigurationProperties从配置文件中获取数据

@Component
public class AliossUtils {
    @Value("${aliyun.oss.endpoint}")
    String endpoint = "https://oss-cn-nanjing.aliyuncs.com";
    @Value("${aliyun.oss.bucketName}")
    String bucketName = "yihengye-test";
    
    EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
     
   
    public AliossUtils() throws ClientException {
    }


    //上传文件,返回最终上传的文件地址
    public  String uploadFile(MultipartFile file) throws IOException {
 		// 创建OSSClient实例。
    	OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        String originName=file.getOriginalFilename();
        //文件名格式为UUID.txt
        // 填写Object完整路径,例如exampledir/exampleobject.txt。Object完整路径中不能包含Bucket名称。
        String objectName = UUID.randomUUID().toString()+originName.substring(originName.lastIndexOf("."));

        ossClient.putObject(bucketName, objectName,  file.getInputStream());
        //返回路径格式:https://yihengye-test.oss-cn-nanjing.aliyuncs.com/text/exerciser.txt
        String result="https://"+bucketName+"."+endpoint.substring(endpoint.lastIndexOf("/")+1)+"/"+objectName;

        return result;
    }
}

当配置文件太多时建议使用@ConfigurationProperties注解进行注入配置。
使用前提:类加入javabean,提供get/set方法,属性名与配置的最后一层名字相同。
改为@ConfigurationProperties的类实现: endpoint、bucketName等配置项会通过ConfigurationProperties注解自动注入

@Component
@Data
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliossUtils {

    String endpoint;
    EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();

    String bucketName ;
    OSS ossClient;
    ...

3.引入Controller层
读取前端传入的文件,用MultipartFile接收,文件以UUID.后缀名保存在阿里oss中(防止同名),返回阿里oss上传的文件地址。

@RestController
@Slf4j
public class HelloController {
    @Autowired
    AliossUtils aliossUtils ;

    public HelloController() throws ClientException {
    }

    @PostMapping("/fileUpload")
    public String file(String name , MultipartFile images) throws IOException {
        String result = aliossUtils.uploadFile(images);
        log.info(result);
        return result;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值