4.6 文件上传
若要实现下方的文件上传页面,需要前后端做如下操作:
后端:
本地存储
云存储
具体实现参考上方连接,不再详细说明
阿里云OSS快速入门请参考文档: AliOSS.md (在talis文件目录下)
1. 导入依赖
<!-- 阿里云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>
2.导入工具类:记得修改 四个属性值为自己的阿里云bucket信息
AliOSSUtils:
package pearl.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.util.UUID;
/**
* 阿里云 OSS 工具类
*/
@Component
public class AliOSSUtils {
private String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
private String accessKeyId = "LTAI5t6shDdHRBipgP6b9nmM";
private String accessKeySecret = "KmrT4ftAXmpswMm8BWdeYy7fIKVSuG";
private String bucketName = "tlias-background-test01pearl";
// 上述四个值一定要修改成自己的信息
/**
* 实现上传图片到OSS
*/
public String upload(MultipartFile file) throws IOException {
// 获取上传的文件的输入流
InputStream inputStream = file.getInputStream();
// 避免文件覆盖
String originalFilename = file.getOriginalFilename();
String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));
//上传文件到 OSS
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
ossClient.putObject(bucketName, fileName, inputStream);
//文件访问路径
String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
// 关闭ossClient
ossClient.shutdown();
return url;// 把上传到oss的路径返回
}
}
新建一个UploadController文件
package pearl.controller;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import pearl.pojo.Result;
import pearl.utils.AliOSSUtils;
import java.io.IOException;
@RestController
@Slf4j
public class UploadController {
@Autowired
private AliOSSUtils aliOSSUtils;
/*
* 文件上传到阿里云
* */
@PostMapping("/upload")
public Result upload(MultipartFile image) throws IOException {
log.info("文件上传,文件名:{}",image.getOriginalFilename());
// 调用阿里云工具类进行文件上传
String url = aliOSSUtils.upload(image);
log.info("文件上传完成,文件访问的url:{}",url);
return Result.success(url);
}
}
完成!
4.7 修改员工
-- 查询回显 - 根据ID查询数据
只用实现根据ID查询数据即可,逻辑与前面的业务类似,不做赘述。
-- 更新数据
逻辑与前面的业务类似,不做赘述。