Java中的文件上传(SpringBoot)(阿里云OSS)

Java中的文件上传(SpringBoot)(阿里云OSS)

使用SpringBoot实现简单的文件上传


enctype属性为mulitpart/form-data,请求方法为post

<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="multipartFile" id="file" value="上传文件">
    <input type="submit" value="submit">
</form>

代码部分:

@RestController  
@RequestMapping("/file")  
public class FileUploadController {
    
      
  
    @PostMapping("/upload")  
    public String uploadAndGoDownLoad(@RequestPart("file") MultipartFile file) throws IOException {
    
      
  
  
        //判断文件夹是否存在  
        String filePath = "E:\\XmpCache";  
        File directoryFile = new File(filePath);  
        if (!directoryFile.exists()) {
    
      
            //创建文件夹  
            directoryFile.mkdirs();  
        }  
  
        //判断文件是否为空  
        if (!file.isEmpty()) {
    
      
            //保存文件  
            file.transferTo(new File(directoryFile, file.getOriginalFilename()));  
        }  
  
        return file.getOriginalFilename();  
    }  
}

阿里云OSS实现文件上传


阿里云OSS是阿里云提供的存储服务,为开发者提供了开发者指南以实现Java、Node.js、php、js等方式的文件上传与下载。

阿里云OSS开发者指南可以在如下入口访问,可以获取相关方法的介绍与实现代码:
在这里插入图片描述
![[Pasted image 20230419171036.png]]
![[Pasted image 20230419171057.png]]

开发者指南中的代码写的很详细,这里就简单贴一个文件上传的代码:

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import java.io.File;

public class Demo {
    
    

    public static void main(String[] args) throws Exception {
    
    
        // Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 阿里云账号AccessKey拥有所有API的访问权限,风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维,请登录RAM控制台创建RAM用户。
        String accessKeyId = "yourAccessKeyId";
        String accessKeySecret = "yourAccessKeySecret";
        // 填写Bucket名称,例如examplebucket。
        String bucketName = "examplebucket";
        // 填写Object完整路径,完整路径中不能包含Bucket名称,例如exampledir/exampleobject.txt。
        String objectName = "exampledir/exampleobject.txt";
        // 填写本地文件的完整路径,例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径,则默认从示例程序所属项目对应本地路径中上传文件。
        String filePath= "D:\\localpath\\examplefile.txt";

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

        try {
    
    
            // 创建PutObjectRequest对象。            
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, new File(filePath));
            // 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。
            // ObjectMetadata metadata = new ObjectMetadata();
            // metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());
            // metadata.setObjectAcl(CannedAccessControlList.Private);
            // putObjectRequest.setMetadata(metadata);

            // 上传文件。
            ossClient.putObject(putObjectRequest);
        } 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();
            }
        }
    }
}

使用阿里云OSS的优点是官方提供了丰富的api,不需要自己写方法;缺点是阿里云OSS是收费服务,若服务被攻击可能会产生巨额费用。因此对于自己的账户要做好安全防护。

猜你喜欢

转载自blog.csdn.net/m0_56170277/article/details/130249022