• Springboot文件上传


    前端代码

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    后端代码

    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";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    修改文件上传最大限制

    文件上传限制默认为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.ossgroupId>
        <artifactId>aliyun-sdk-ossartifactId>
        <version>3.15.1version>
    dependency>
    
    <dependency>
        <groupId>javax.xml.bindgroupId>
        <artifactId>jaxb-apiartifactId>
        <version>2.3.1version>
    dependency>
    <dependency>
        <groupId>javax.activationgroupId>
        <artifactId>activationartifactId>
        <version>1.1.1version>
    dependency>
    
    <dependency>
        <groupId>org.glassfish.jaxbgroupId>
        <artifactId>jaxb-runtimeartifactId>
        <version>2.3.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    上传文件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();
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    整合到web项目中

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

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

    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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    当配置文件太多时建议使用@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;
        ...
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
  • 相关阅读:
    网站一键灰色
    卷积神经网络的常用改进
    python函数print()
    表格数据方法、分页方法及组件的封装和分页组件的复用
    机器人 Null impedance(零阻抗)梳理
    创建hive事物表(模拟测试)
    Demo26字母异位词
    git删除commit的历史大文件记录
    独有且优质,这些Mac软件绝了
    仿黑马点评-redis整合【三、缓存工具封装】
  • 原文地址:https://blog.csdn.net/weixin_44866921/article/details/133713723