概述
这个模块是用来上传头像以及文章封面的,图片的值是一个地址字符串,一般存放在本地或阿里云服务中
1、本地文件上传
我们将文件保存在一个本地的文件夹下,由于可能两个人上传不同图片但是却同名的图片,那么就会一个人的图片就会覆盖住另一个人的图片。因此我们需要使用UUID来保证我们的图片名字不重复。
tomcat默认的最大文件上传大小为1mb,超过就会报错,我们可以更改一下配置
spring:servlet:multipart.max-file-size: 50MBmultipart.max-request-size: 50MBserver:max-http-form-post-size: -1
代码实现
Controller
@RestController
public class FileUploadController {@PostMapping("/upload")public Result<String> upload(MultipartFile file) throws IOException {//把文件的内容String originalFilename = file.getOriginalFilename();//保证文件的名字是唯一的,后缀加上.pngString fileName = UUID.randomUUID().toString() +originalFilename.substring(originalFilename.lastIndexOf("."));file.transferTo(new File("D:\\JAVA_project\\big-event\\src\\main\\resources\\static\\files\\" +fileName));return Result.success("url访问地址...");}
}
测试
上传同一个文件三次且没有覆盖
2、阿里云OSS
云
非官方解释:互联网上的一些远程服务器,可供你使用。
阿里云是阿里巴巴集团下全球领先的云计算公司,也是国内最大的云服务提供商。
我们选择阿里云OSS云服务器,第一次使用赠送三个月20G的试用
我们直接将图片或文件直接存储在阿里云oss上即可
创建一个bucket
进入bucket
点击AccessKey管理
创建一个AccessKey,这个就相当于账号和密码了,不要泄露
使用方法
引入依赖
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.15.1</version>
</dependency>
如果使用的是Java 9及以上的版本,则需要添加jaxb相关依赖。添加jaxb相关依赖示例代码如下
<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拿过来改成我们自己的工具类
package com.wal.bigevent.util;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 com.aliyun.oss.model.PutObjectResult;import java.io.File;
import java.io.InputStream;public class AliOssUtil {// Endpoint以华东1(杭州)为例,其它Region请按实际情况填写。private static final String Endpoint = "https://oss-cn-beijing.aliyuncs.com";// 填写Bucket名称,例如examplebucket。private static final String bucketName = "big-event-wal";private static final String AccessKeyId = "LTAI5tCLBwaVPB2MA3Lhu2vo";private static final String AccessKeySecret = "q0j64AWJkJG2LMH8oDycfomen8saV1";public static String uploadFile(String objectName, InputStream in) throws Exception {
// EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();// 创建OSSClient实例。OSS ossClient = new OSSClientBuilder().build(Endpoint,AccessKeyId,AccessKeySecret);String url = "";try {// 填写字符串。String content = "Hello OSS,你好世界";// 创建PutObjectRequest对象。PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName,objectName ,in);// 如果需要上传时设置存储类型和访问权限,请参考以下示例代码。// ObjectMetadata metadata = new ObjectMetadata();// metadata.setHeader(OSSHeaders.OSS_STORAGE_CLASS, StorageClass.Standard.toString());// metadata.setObjectAcl(CannedAccessControlList.Private);// putObjectRequest.setMetadata(metadata);// 上传字符串。PutObjectResult result = ossClient.putObject(putObjectRequest);url = "https://" + bucketName + "." + Endpoint.substring(Endpoint.lastIndexOf("/") + 1)+ "/" +objectName;} 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();}}return url;}
}
将之前的本地上传的Controller更改
@RestController
public class FileUploadController {@PostMapping("/upload")public Result<String> upload(MultipartFile file) throws Exception {//把文件的内容String originalFilename = file.getOriginalFilename();//保证文件的名字是唯一的,后缀加上.pngString fileName = UUID.randomUUID().toString() +originalFilename.substring(originalFilename.lastIndexOf("."));// file.transferTo(new File("D:\\JAVA_project\\big-event\\src\\main\\resources\\static\\files\\" +
// fileName));String url = AliOssUtil.uploadFile(fileName, file.getInputStream());return Result.success(url);}
}
测试