File upload in Java (SpringBoot) (Alibaba Cloud OSS)

File upload in Java (SpringBoot) (Alibaba Cloud OSS)

Simple file upload using SpringBoot


The enctype attribute is mulitpart/form-data, and the request method is post

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

code part:

@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();  
    }  
}

Alibaba Cloud OSS implements file upload


Alibaba Cloud OSS is a storage service provided by Alibaba Cloud. It provides developers with developer guides to upload and download files in Java, Node.js, php, and js.

Alibaba Cloud OSS Developer Guide can be accessed at the following entry, where you can get the introduction and implementation code of related methods:
insert image description here
![[Pasted image 20230419171036.png]]
![[Pasted image 20230419171057.png]]

The code in the developer guide is very detailed, here is a simple code for uploading a file:

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();
            }
        }
    }
}

The advantage of using Alibaba Cloud OSS is that the official provides rich APIs, and you don’t need to write methods yourself; the disadvantage is that Alibaba Cloud OSS is a paid service, and huge fees may be incurred if the service is attacked. Therefore, it is necessary to protect the security of your own account.

Guess you like

Origin blog.csdn.net/m0_56170277/article/details/130249022