oss文件上传接口

This commit is contained in:
kuang.yife 2023-12-10 14:45:48 +08:00
parent 09ad8e33fe
commit 9287270fdb
8 changed files with 140 additions and 184 deletions

View File

@ -1,8 +1,12 @@
package com.ruoyi;
import com.aliyun.oss.OSSClient;
import com.ruoyi.web.core.config.OssConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.context.annotation.Bean;
/**
* 启动程序
@ -12,6 +16,9 @@ import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
@SpringBootApplication(exclude = { DataSourceAutoConfiguration.class })
public class RuoYiApplication
{
@Autowired
private OssConfig ossConfig;
public static void main(String[] args)
{
// System.setProperty("spring.devtools.restart.enabled", "false");
@ -27,4 +34,10 @@ public class RuoYiApplication
" | | \\ / \\ / \n" +
" ''-' `'-' `-..-' ");
}
@Bean
public OSSClient OssClient() {
return new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
}
}

View File

@ -0,0 +1,34 @@
package com.ruoyi.web.controller.tool;
import com.ruoyi.common.core.domain.Result;
import com.ruoyi.web.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
/**
* <p>文件上传</p>
* @author clunt
*/
@RestController
@Api(tags = "App*文件上传")
@RequestMapping(value = "/tool/oss")
public class OssFileController {
@Autowired
private OssService ossService;
@ResponseBody
@PostMapping(value = "/upload")
@ApiOperation(value = "文件上传接口,返回文件的url地址")
public Result<String> upload(@RequestPart @RequestParam("file") MultipartFile multipartFile) {
try {
return Result.success(ossService.upload(multipartFile));
}catch (Exception e){
return Result.error(e.getMessage());
}
}
}

View File

@ -1,183 +0,0 @@
package com.ruoyi.web.controller.tool;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
/**
* swagger 用户测试方法
*
* @author ruoyi
*/
@Api("用户信息管理")
@RestController
@RequestMapping("/test/user")
public class TestController extends BaseController
{
private final static Map<Integer, UserEntity> users = new LinkedHashMap<Integer, UserEntity>();
{
users.put(1, new UserEntity(1, "admin", "admin123", "15888888888"));
users.put(2, new UserEntity(2, "ry", "admin123", "15666666666"));
}
@ApiOperation("获取用户列表")
@GetMapping("/list")
public R<List<UserEntity>> userList()
{
List<UserEntity> userList = new ArrayList<UserEntity>(users.values());
return R.ok(userList);
}
@ApiOperation("获取用户详细")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
@GetMapping("/{userId}")
public R<UserEntity> getUser(@PathVariable Integer userId)
{
if (!users.isEmpty() && users.containsKey(userId))
{
return R.ok(users.get(userId));
}
else
{
return R.fail("用户不存在");
}
}
@ApiOperation("新增用户")
@ApiImplicitParams({
@ApiImplicitParam(name = "userId", value = "用户id", dataType = "Integer", dataTypeClass = Integer.class),
@ApiImplicitParam(name = "username", value = "用户名称", dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(name = "password", value = "用户密码", dataType = "String", dataTypeClass = String.class),
@ApiImplicitParam(name = "mobile", value = "用户手机", dataType = "String", dataTypeClass = String.class)
})
@PostMapping("/save")
public R<String> save(UserEntity user)
{
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
{
return R.fail("用户ID不能为空");
}
users.put(user.getUserId(), user);
return R.ok();
}
@ApiOperation("更新用户")
@PutMapping("/update")
public R<String> update(@RequestBody UserEntity user)
{
if (StringUtils.isNull(user) || StringUtils.isNull(user.getUserId()))
{
return R.fail("用户ID不能为空");
}
if (users.isEmpty() || !users.containsKey(user.getUserId()))
{
return R.fail("用户不存在");
}
users.remove(user.getUserId());
users.put(user.getUserId(), user);
return R.ok();
}
@ApiOperation("删除用户信息")
@ApiImplicitParam(name = "userId", value = "用户ID", required = true, dataType = "int", paramType = "path", dataTypeClass = Integer.class)
@DeleteMapping("/{userId}")
public R<String> delete(@PathVariable Integer userId)
{
if (!users.isEmpty() && users.containsKey(userId))
{
users.remove(userId);
return R.ok();
}
else
{
return R.fail("用户不存在");
}
}
}
@ApiModel(value = "UserEntity", description = "用户实体")
class UserEntity
{
@ApiModelProperty("用户ID")
private Integer userId;
@ApiModelProperty("用户名称")
private String username;
@ApiModelProperty("用户密码")
private String password;
@ApiModelProperty("用户手机")
private String mobile;
public UserEntity()
{
}
public UserEntity(Integer userId, String username, String password, String mobile)
{
this.userId = userId;
this.username = username;
this.password = password;
this.mobile = mobile;
}
public Integer getUserId()
{
return userId;
}
public void setUserId(Integer userId)
{
this.userId = userId;
}
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public String getMobile()
{
return mobile;
}
public void setMobile(String mobile)
{
this.mobile = mobile;
}
}

View File

@ -0,0 +1,22 @@
package com.ruoyi.web.core.config;
import com.aliyun.oss.OSSClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@ConfigurationProperties(prefix = "aliyun")
@Data
public class OssConfig {
private String endpoint;
private String accessKeyId;
private String accessKeySecret;
private String bucketName;
private String urlPrefix;
}

View File

@ -0,0 +1,9 @@
package com.ruoyi.web.service;
import org.springframework.web.multipart.MultipartFile;
public interface OssService {
String upload(MultipartFile multipartFile) throws Exception;
}

View File

@ -0,0 +1,51 @@
package com.ruoyi.web.service.impl;
import cn.hutool.core.date.DateTime;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.PutObjectResult;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.web.core.config.OssConfig;
import com.ruoyi.web.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
@Slf4j
@Service
public class OssServiceImpl implements OssService {
@Autowired
private OSSClient ossClient;
@Autowired
private OssConfig ossConfig;
@Override
public String upload(MultipartFile multipartFile) throws Exception{
String filePath = getFilePath(multipartFile.getOriginalFilename());
// 上传到阿里云
try {
PutObjectResult ossResult = ossClient.putObject(ossConfig.getBucketName(), filePath, new
ByteArrayInputStream(multipartFile.getBytes()));
log.info("上传文件到OSS结果:{}", ossResult.getResponse());
} catch (Exception e) {
log.error(ExceptionUtil.getExceptionMessage(e));
throw new Exception(e.getMessage());
}
return ossConfig.getUrlPrefix() + filePath;
}
private String getFilePath(String sourceFileName) {
DateTime dateTime = new DateTime();
return "images/" + dateTime.toString("yyyy")
+ "/" + dateTime.toString("MM") + "/"
+ dateTime.toString("dd") + "/" + System.currentTimeMillis() +
RandomUtils.nextInt(100, 9999) + "." +
StringUtils.substringAfterLast(sourceFileName, ".");
}
}

View File

@ -166,3 +166,11 @@ youban:
template-code: SMS_463638490
access-key: LTAI5tSVfRSePk9cfLUT5y5f
secret: qlpXG6usf0zPgQQECDAlrfYoMRHxgM
aliyun:
access-key-id: LTAI5tSVfRSePk9cfLUT5y5f
access-key-secret: qlpXG6usf0zPgQQECDAlrfYoMRHxgM
bucket-name: youban2023
endpoint: http://oss-cn-shenzhen.aliyuncs.com
url-prefix: http://youban2023.oss-cn-shenzhen.aliyuncs.com/

View File

@ -294,8 +294,10 @@ public class ShiroConfig
filterChainDefinitionMap.put("/login", "anon,captchaValidate");
// 注册相关
filterChainDefinitionMap.put("/register", "anon,captchaValidate");
// 短信文档
// 短信接口
filterChainDefinitionMap.put("/tool/sms/**", "anon");
// oss文件接口
filterChainDefinitionMap.put("/tool/oss/**", "anon");
// app登陆接口
filterChainDefinitionMap.put("/app/login/**", "anon");
// 系统权限列表