更新文件上传接口

This commit is contained in:
p71924506 2022-07-19 09:27:32 +08:00
parent 8fd195e254
commit 1143acfe44
7 changed files with 402 additions and 0 deletions

View File

@ -0,0 +1,17 @@
package com.osredm.codescan.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @program:letoy-study-java
* @author: WeiHaoL
* @Time: 2021/2/5 下午8:15
*/
@Component
@ConfigurationProperties(prefix="file")
@Data
public class StoreConfig {
private String filePath;
}

View File

@ -0,0 +1,66 @@
package com.osredm.codescan.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.core.env.Profiles;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.ArrayList;
@Configuration
// 开启Swagger2
@EnableSwagger2
public class SwaggerConfig {
// 配置Swagger的Docket bean实例
@Bean
public Docket docket(Environment environment) {
// 设置要显示的Swagger环境
Profiles profiles = Profiles.of("dev", "test","lwh","win","desk","lwhWin");
// 通过environment.acceptsProfiles判断是否在自己设定的环境当中
boolean flag = environment.acceptsProfiles(profiles);
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(flag) // 是否启动
.groupName("developer")
.select()
//RequestHandlerSelectors 配置要扫描接口的方式
//basePackage 指定要扫描的包
//any();扫描全部
//none() 都不扫描
// withClassAnnotation()扫描类上的注解 需要注解的class
//withMethodAnnotation 扫描方法上的注解
.apis(RequestHandlerSelectors.basePackage("com.osredm.osredmcompbackend.controller"))
// 过滤 什么 路径
// .paths(PathSelectors.ant("/user"))
.build();
}
// 配置Swagger信息 apiinfo
private ApiInfo apiInfo() {
// 作者信息
Contact contact = new Contact("SkyID", "https://osredm.com", "123");
return new ApiInfo("osredm-comp-custom API DOC",
"这是一个描述 我也不知道写点啥",
"1.0",
"urn:tos",
contact,
"Apache 2.0",
"http://www.apache.org/licenses/LICENSE-2.0",
new ArrayList());
}
}

View File

@ -0,0 +1,39 @@
package com.osredm.codescan.controller;
import com.osredm.codescan.config.StoreConfig;
import com.osredm.codescan.utils.FileUploadUtil;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.util.HashMap;
import java.util.Objects;
import static com.osredm.codescan.utils.Constants.FAIL;
import static com.osredm.codescan.utils.Constants.SUCCESS;
@RestController
@RequestMapping("/upload")
public class UploadController {
private final StoreConfig storeConfig;
public UploadController(StoreConfig storeConfig) {
this.storeConfig = storeConfig;
}
@PostMapping("/renameFiles")
private HashMap<String, Object> renameFiles(MultipartFile file,String type){
HashMap<String, Object> map = new HashMap<>();
String fileName = System.currentTimeMillis() +"-"+ type + "-" + file.getOriginalFilename();
boolean result = FileUploadUtil.uploadFileWithName(file, storeConfig.getFilePath(), fileName);
if (result) {
map.put("status",SUCCESS);
map.put("url","/api/files/"+ fileName);
}else {
map.put("status",FAIL);
}
return map;
}
}

View File

@ -0,0 +1,69 @@
package com.osredm.codescan.utils;
public class Constants {
//激活码不存在
public static final int CODE_NOT_EXIST = 3;
//邮箱已经被使用
public static final int PHONE_ALREADY_USE = 4;
//激活码超时
public static final int CODE_TIME_INVALID = 5;
//激活码错误
public static final int CODE_INVALID = 6;
//账号或者密码错误
public static final int PASSWORD_INCORRECT = 7;
//预期外的错误
public static final int EXCEPTED_SYSTEM_ERROR = 8;
//一般指数据库的操作或者正常操作中出现的异常
public static final int SYSTEM_ERROR = 10;
//操作返回失败
public static final int FAIL = 10;
//发送邮件系统异常
public static final int SYSTEM_ERROR_MAIL_SEND_FAIL = 11;
//用户不合法
public static final int SYSTEM_ERROR_USER_INVALID = 12;
//用户权限不够
public static final int SYSTEM_ERROR_USER_LEVEL_INVALID = 13;
//用户尚未激活
public static final int SYSTEM_ERROR_USER_NOT_ACTIVATE = 14;
public static final int SUCCESS = 0;
// 上传失败
public static final int UPLOAD_FAIL = 20;
public static String getMsg(int ERROR_CODE) {
String msg = "";
switch (ERROR_CODE) {
case SYSTEM_ERROR_USER_LEVEL_INVALID:
return "INSUFFICIENT USER ACCESS";
case SYSTEM_ERROR_USER_NOT_ACTIVATE:
return "USER NOT ACTIVATED";
case SYSTEM_ERROR_USER_INVALID:
return "USER NOT LOGIN";
case SYSTEM_ERROR:
return "PLEASE TRY AGAIN";
case CODE_TIME_INVALID:
return "激活码失效";
case CODE_INVALID:
return "CODE ERROR";
case PASSWORD_INCORRECT:
return "PASSWORD INCORRECT";
case CODE_NOT_EXIST:
return "激活码不存在";
case EXCEPTED_SYSTEM_ERROR:
return "系统错误请稍后再试";
}
return msg;
}
}

View File

@ -0,0 +1,133 @@
package com.osredm.codescan.utils;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
/**
* @program:letoy-study-java
* @author: WeiHaoL
* @Time: 2021/2/4 下午3:40
*/
public class FileUploadUtil {
public static boolean uploadFileWithName(MultipartFile file, String filePath,String fileName){
if (file.isEmpty()) {
return false;
}
try {
File dest = new File(filePath + fileName);
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
public static boolean uploadFile(MultipartFile file, String filePath){
if (file.isEmpty()) {
return false;
}
try {
String filename = RandomUtil.getUid() + "-" + file.getOriginalFilename();
File dest = new File(filePath + filename);
if (!dest.getParentFile().exists()){
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
return true;
}catch (Exception e){
e.printStackTrace();
return false;
}
}
public static void updateFile(String filePath,String content) throws IOException {
File dir = new File(filePath);
// 检查放置文件的文件夹路径是否存在不存在则创建
if (!dir.exists()) {
dir.mkdirs();// mkdirs创建多级目录
}
File checkFile = new File(filePath +System.currentTimeMillis() +"-AutoUpdate.log");
FileWriter writer = null;
try {
// 检查目标文件是否存在不存在则创建
if (!checkFile.exists()) {
checkFile.createNewFile();// 创建目标文件
}
// 向目标文件中写入内容
// FileWriter(File file, boolean append)append为true时为追加模式false或缺省则为覆盖模式
writer = new FileWriter(checkFile, true);
writer.append(content);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != writer)
writer.close();
}
}
public static boolean uploadHtml(String filePath,String content,String fileName) throws IOException {
File dir = new File(filePath);
// 检查放置文件的文件夹路径是否存在不存在则创建
if (!dir.exists()) {
dir.mkdirs();// mkdirs创建多级目录
}
File checkFile = new File(filePath +fileName);
FileWriter writer = null;
try {
// 检查目标文件是否存在不存在则创建
if (!checkFile.exists()) {
checkFile.createNewFile();// 创建目标文件
}
// 向目标文件中写入内容
// FileWriter(File file, boolean append)append为true时为追加模式false或缺省则为覆盖模式
writer = new FileWriter(checkFile, false);
writer.append(content);
writer.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
} finally {
if (null != writer)
writer.close();
}
}
public static String readFile(String path){
//java 8中这样写也可以
try (BufferedReader br = Files.newBufferedReader(Paths.get(path))){
String line = "";
String line1;
while ((line1 = br.readLine()) != null) {
line = line + line1 + '\n' ;
}
return line;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
}

View File

@ -0,0 +1,50 @@
package com.osredm.codescan.utils;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Random;
import java.util.UUID;
public class RandomUtil {
public static String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
"g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
"t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
"6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
public static String generateShortUuid() {
StringBuffer shortBuffer = new StringBuffer();
String uuid = UUID.randomUUID().toString().replace("-", "");
for (int i = 0; i < 6; i++) {
String str = uuid.substring(i * 4, i * 4 + 4);
int x = Integer.parseInt(str, 16);
shortBuffer.append(chars[x % 0x3E]);
}
return shortBuffer.toString();
}
public static String getRandomId() {
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}
public static String getCode() {
int max = 999999, min = 100000;
Random random = new Random();
int code = random.nextInt(max) % (max - min + 1) + min;
return String.valueOf(code);
}
public static int getUid(){
Calendar c= Calendar.getInstance();
String time=new SimpleDateFormat("yyyy-MM-ddHHmmss").format(c.getTime()).toString();
StringBuffer s=new StringBuffer(time.substring(14, 16));
Long sys=System.currentTimeMillis();
s.append(sys.toString().substring(11, 13));
Double tm=Math.random()*10000+1;
s.append(tm.toString().substring(tm.toString().length()-4, tm.toString().length()));
int uid = Integer.parseInt(String.valueOf(s));
return uid;
}
}

View File

@ -0,0 +1,28 @@
server.port=8011
#MyBatis
mybatis_config_file=mybatis-config.xml
mapper_path=/mapper/**.xml
entity_package=com.osredm.codescan.entity,com.osredm.codescan.vo
#MySQL
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://114.116.228.69:8006/osredm_comp?useUnicode=true&characterEncoding=utf8&useSSL=false&allowPublicKeyRetrieval=true&allowMultiQueries=true
spring.datasource.username=root
spring.datasource.password=HskyOsredm@163.com
#swagger
spring.mvc.pathmatch.matching-strategy=ant_path_matcher
localPath=file:C:/Users/xmb_jsz/Desktop/NoCheat/
#/root/NoCheat
fileUploadPath=C://Users//xmb_jsz//Desktop//NoCheat//
file.filePath=C://Users//xmb_jsz//Desktop//NoCheat//
domain=http://localhost:8010/
spring.servlet.multipart.max-file-size = 1000MB
spring.servlet.multipart.max-request-size=10000MB