feat: 上传接口实现

This commit is contained in:
张松
2024-12-11 10:27:47 +08:00
parent eea45c05d8
commit b1a9894a33
7 changed files with 167 additions and 46 deletions

View File

@@ -21,6 +21,11 @@
</properties> </properties>
<dependencies> <dependencies>
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>2.8.3</version>
</dependency>
<!-- zxing生成二维码 --> <!-- zxing生成二维码 -->
<dependency> <dependency>
<groupId>com.google.zxing</groupId> <groupId>com.google.zxing</groupId>

View File

@@ -5,9 +5,13 @@ import com.chaozhanggui.system.cashierservice.entity.dto.ClearTableDTO;
import com.chaozhanggui.system.cashierservice.service.ShopInfoService; import com.chaozhanggui.system.cashierservice.service.ShopInfoService;
import com.chaozhanggui.system.cashierservice.sign.CodeEnum; import com.chaozhanggui.system.cashierservice.sign.CodeEnum;
import com.chaozhanggui.system.cashierservice.sign.Result; import com.chaozhanggui.system.cashierservice.sign.Result;
import com.chaozhanggui.system.cashierservice.util.AliUploadUtils;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*; import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
@CrossOrigin(origins = "*") @CrossOrigin(origins = "*")
@RestController @RestController
@@ -78,4 +82,9 @@ public class ShopInfoController {
public Result queryPwdInfo(@RequestParam("shopId") String shopId) { public Result queryPwdInfo(@RequestParam("shopId") String shopId) {
return shopInfoService.queryShopPwdInfo(shopId); return shopInfoService.queryShopPwdInfo(shopId);
} }
@PostMapping("upload")
public Result upload(@RequestParam("file") MultipartFile file) throws Exception {
return Result.success(CodeEnum.SUCCESS, AliUploadUtils.uploadSuffix(file.getInputStream(), file.getOriginalFilename()));
}
} }

View File

@@ -16,12 +16,15 @@ public class CustomFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException { public void init(FilterConfig filterConfig) throws ServletException {
log.info(">>>> customFilter init <<<<"); log.info(">>>> customFilter init <<<<");
} }
public boolean isMultipartRequest(HttpServletRequest request) {
String contentType = request.getContentType();
return contentType != null && contentType.toLowerCase().startsWith("multipart/form-data");
}
@Override @Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
log.info(">>>> customFilter doFilter start <<<<"); log.info(">>>> customFilter doFilter start <<<<");
RequestWrapper requestWapper = null; RequestWrapper requestWapper = null;
if (servletRequest instanceof HttpServletRequest) { if (servletRequest instanceof HttpServletRequest && !isMultipartRequest((HttpServletRequest)servletRequest)) {
requestWapper = new RequestWrapper((HttpServletRequest) servletRequest); requestWapper = new RequestWrapper((HttpServletRequest) servletRequest);
} }

View File

@@ -1,5 +1,7 @@
package com.chaozhanggui.system.cashierservice.interceptor; package com.chaozhanggui.system.cashierservice.interceptor;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.ReadListener; import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream; import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
@@ -9,73 +11,70 @@ import java.io.*;
public class RequestWrapper extends HttpServletRequestWrapper { public class RequestWrapper extends HttpServletRequestWrapper {
private final String body; private final String body;
public RequestWrapper(HttpServletRequest request) { public RequestWrapper(HttpServletRequest request) throws IOException {
super(request); super(request);
StringBuilder stringBuilder = new StringBuilder(); StringBuilder stringBuilder = new StringBuilder();
BufferedReader bufferedReader = null; BufferedReader bufferedReader = null;
InputStream inputStream = null; InputStream inputStream = null;
try {
// 仅处理普通请求体不影响multipart请求
if (!(request instanceof MultipartHttpServletRequest)) {
inputStream = request.getInputStream(); inputStream = request.getInputStream();
if (inputStream != null) { if (inputStream != null) {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
char[] charBuffer = new char[128]; char[] charBuffer = new char[128];
int bytesRead = -1; int bytesRead;
while ((bytesRead = bufferedReader.read(charBuffer)) > 0) { while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
stringBuilder.append(charBuffer, 0, bytesRead); stringBuilder.append(charBuffer, 0, bytesRead);
} }
} else { } else {
stringBuilder.append(""); stringBuilder.append("");
} }
} catch (IOException ex) { body = stringBuilder.toString();
ex.printStackTrace(); } else {
} finally { // 如果是Multipart请求不做处理直接返回
if (inputStream != null) { body = null;
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
if (bufferedReader != null) {
try {
bufferedReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
} }
body = stringBuilder.toString();
} }
@Override @Override
public ServletInputStream getInputStream() throws IOException { public ServletInputStream getInputStream() throws IOException {
final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes()); if (body != null) {
ServletInputStream servletInputStream = new ServletInputStream() { final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(body.getBytes());
@Override return new ServletInputStream() {
public boolean isFinished() { @Override
return false; public boolean isFinished() {
} return byteArrayInputStream.available() == 0;
@Override }
public boolean isReady() {
return false;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
return servletInputStream;
@Override
public boolean isReady() {
return byteArrayInputStream.available() > 0;
}
@Override
public void setReadListener(ReadListener readListener) {
}
@Override
public int read() throws IOException {
return byteArrayInputStream.read();
}
};
} else {
// 如果是Multipart请求返回空的输入流交给Spring处理
return super.getInputStream();
}
} }
@Override @Override
public BufferedReader getReader() throws IOException { public BufferedReader getReader() throws IOException {
return new BufferedReader(new InputStreamReader(this.getInputStream())); if (body != null) {
return new BufferedReader(new InputStreamReader(this.getInputStream()));
} else {
// 如果是Multipart请求返回空的reader
return super.getReader();
}
} }
public String getBody() { public String getBody() {

View File

@@ -15,6 +15,7 @@ import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@@ -121,7 +122,7 @@ public class SignInterceptor implements HandlerInterceptor {
* @param request * @param request
* @return * @return
*/ */
private Map<String, Object> getParameterMap(HttpServletRequest request) { private Map<String, Object> getParameterMap(HttpServletRequest request) throws IOException {
RequestWrapper requestWrapper = new RequestWrapper(request); RequestWrapper requestWrapper = new RequestWrapper(request);
String body = requestWrapper.getBody(); String body = requestWrapper.getBody();
if (ObjectUtil.isNotEmpty(body)) { if (ObjectUtil.isNotEmpty(body)) {

View File

@@ -0,0 +1,94 @@
/**
* Copyright (c) 2018 人人开源 All rights reserved.
*
* https://www.renren.io
*
* 版权所有,侵权必究!
*/
package com.chaozhanggui.system.cashierservice.util;
import com.aliyun.oss.OSSClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.UUID;
/**
* 阿里云存储
*
* @author Mark sunlightcs@gmail.com
*/
@Component
public class AliUploadUtils {
private static String secret;
private static String key;
private static String endPoint;
private static String bucketName;
private static String prefix;
private static String url;
// 构造器注入
public AliUploadUtils(@Value("${aliyun.keysecret}") String secret,
@Value("${aliyun.keyid}") String key,
@Value("${aliyun.oss.endpoint}") String endPoint,
@Value("${aliyun.oss.bucketname}") String bucketName,
@Value("${aliyun.prefix}") String prefix,
@Value("${aliyun.url}") String url) {
AliUploadUtils.secret = secret;
AliUploadUtils.key = key;
AliUploadUtils.endPoint = endPoint;
AliUploadUtils.bucketName = bucketName;
AliUploadUtils.prefix = prefix;
AliUploadUtils.url = url;
}
/**
* 文件路径
* @param prefix 前缀
* @param suffix 后缀
* @return 返回上传路径
*/
public static String getPath(String prefix, String suffix) {
//生成uuid
String uuid = UUID.randomUUID().toString().replaceAll("-", "");
//文件路径
String path = DateUtils.getDays() + "/" + uuid;
if(StringUtils.isNotBlank(prefix)){
path = prefix + "/" + path;
}
return path + "." + suffix;
}
public static String upload(InputStream inputStream, String path) throws Exception {
OSSClient client = new OSSClient(endPoint, key,
secret);
try {
client.putObject(bucketName, path, inputStream);
client.shutdown();
} catch (Exception e){
throw new Exception("上传异常");
}
return "https://"+ url + "/" + path;
}
public static String uploadSuffix(InputStream inputStream, String fileName) throws Exception {
return upload(inputStream, getPath(prefix, getFileExtension(fileName)));
}
public static String getFileExtension(String fileName) {
int dotIndex = fileName.lastIndexOf(".");
if (dotIndex > 0) {
return fileName.substring(dotIndex).replace(".", "");
} else {
return "";
}
}
}

View File

@@ -83,3 +83,13 @@ mybatis-plus:
# php服务器地址 # php服务器地址
phpServer: https://czgdoumei.sxczgkj.com/index.php/api phpServer: https://czgdoumei.sxczgkj.com/index.php/api
# oss配置
aliyun:
prefix: upload
keyid: LTAI5tPdEfYSZcqHbjCrtPRD
keysecret: DZjyHBq3nTujF0NMLxnZgsecU8ZCvy
url: cashier-oss.oss-cn-beijing.aliyuncs.com
oss:
bucketname: cashier-oss
endpoint: oss-cn-beijing.aliyuncs.com