Commit 04b3a344 authored by 以墨为白's avatar 以墨为白 🎧

图片上传

parent 9425013f
package com.zksy.szpt.controller;
import com.zksy.szpt.domain.UploadImageDTO;
import com.zksy.szpt.service.ImageUploadService;
import io.swagger.annotations.Api;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@Api(tags = "文件上传管理")
@RequestMapping("/rest/image")
@RestController
public class ImageUploadController {
private final ImageUploadService imageUploadService;
public ImageUploadController(ImageUploadService imageUploadService) {
this.imageUploadService = imageUploadService;
}
@PostMapping("/upload")
public Integer upload(@RequestBody @Validated UploadImageDTO uploadImageDTO) {
return imageUploadService.upload(uploadImageDTO);
}
}
package com.zksy.szpt.domain;
public enum ListImageType {
FACE,
BODY
}
package com.zksy.szpt.domain;
import javax.validation.constraints.NotBlank;
public class UploadImageDTO {
@NotBlank(message = "图片路径不能为空")
private String imagePath;
private ListImageType imageType;
public String getImagePath() {
return imagePath;
}
public void setImagePath(String imagePath) {
this.imagePath = imagePath;
}
public ListImageType getImageType() {
return imageType;
}
public void setImageType(ListImageType imageType) {
this.imageType = imageType;
}
}
package com.zksy.szpt.domain.po; package com.zksy.szpt.domain.po;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import java.util.Date; import java.util.Date;
@TableName("xx_imgfile")
public class XxImgfile { public class XxImgfile {
/** /**
* 图片IID * 图片IID
...@@ -11,6 +16,7 @@ public class XxImgfile { ...@@ -11,6 +16,7 @@ public class XxImgfile {
/** /**
* 图片ID * 图片ID
*/ */
@TableId(type = IdType.ASSIGN_ID)
private String id; private String id;
/** /**
......
package com.zksy.szpt.exception;
/**
* 其他主动抛出的信息
*/
public class NotificationException extends Exception {
//异常信息
private String message;
//构造函数
public NotificationException(String message) {
super(message);
this.message = message;
}
}
package com.zksy.szpt.mapper; package com.zksy.szpt.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zksy.szpt.domain.po.XxImgfile; import com.zksy.szpt.domain.po.XxImgfile;
import com.zksy.szpt.domain.po.XxImgfileExample; import com.zksy.szpt.domain.po.XxImgfileExample;
import java.util.List; import java.util.List;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
public interface XxImgfileMapper { public interface XxImgfileMapper extends BaseMapper<XxImgfile> {
long countByExample(XxImgfileExample example); long countByExample(XxImgfileExample example);
int deleteByExample(XxImgfileExample example); int deleteByExample(XxImgfileExample example);
int deleteByPrimaryKey(Long iid); int deleteByPrimaryKey(Long iid);
int insert(XxImgfile record); // int insert(XxImgfile record);
int insertSelective(XxImgfile record); int insertSelective(XxImgfile record);
......
package com.zksy.szpt.service;
import com.zksy.szpt.domain.UploadImageDTO;
import com.zksy.szpt.domain.po.XxImgfile;
import com.zksy.szpt.exception.NotificationException;
import com.zksy.szpt.mapper.XxImgfileMapper;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import reactor.core.publisher.Mono;
import java.net.URISyntaxException;
@Service
public class ImageUploadService {
private final XxImgfileMapper xxImgfileMapper;
public ImageUploadService(XxImgfileMapper xxImgfileMapper) {
this.xxImgfileMapper = xxImgfileMapper;
}
public Integer upload(UploadImageDTO uploadImageDTO) {
// 创建 WebClient 实例用于下载文件
WebClient webClient = WebClient.builder()
.baseUrl(uploadImageDTO.getImagePath())
.build();
// 下载文件到内存中的字节数组
Mono<byte[]> fileContentMono = webClient.get()
.uri("")
.retrieve()
.bodyToMono(byte[].class)
.onErrorResume(WebClientResponseException.class, ex -> {
System.err.println("WebClientResponseException: " + ex.getResponseBodyAsString());
return Mono.error(new NotificationException(uploadImageDTO.getImagePath() + ",Failed to download file: " + ex.getStatusText()));
})
.onErrorResume(URISyntaxException.class, ex -> {
System.err.println("URISyntaxException: " + ex.getMessage());
return Mono.error(new NotificationException(uploadImageDTO.getImagePath() + ",Invalid URL format"));
})
.onErrorResume(Exception.class, ex -> {
System.err.println("General Exception: " + ex.getMessage());
return Mono.error(new NotificationException(uploadImageDTO.getImagePath() + ",An error occurred while downloading the file"));
});
XxImgfile xxImgfile = new XxImgfile();
xxImgfile.setOurl(uploadImageDTO.getImagePath());
xxImgfile.setNwzh("0");
// 等待文件内容下载完成
byte[] fileContent = fileContentMono.block();
xxImgfile.setData(fileContent);
return xxImgfileMapper.insert(xxImgfile);
// 将文件内容插入数据库
// fileContentMono.flatMap(fileContent -> {
// try {
// xxImgfile.setData(fileContent);
// return Mono.just(xxImgfileMapper.insert(xxImgfile));
// } catch (Exception e) {
// e.printStackTrace();
// return Mono.error(e);
// }
// }).subscribe(rowsAffected -> {
// System.out.println("Rows affected: " + rowsAffected);
// }, error -> {
// error.printStackTrace();
// });
}
}
...@@ -3,6 +3,8 @@ package com.zksy.szpt; ...@@ -3,6 +3,8 @@ package com.zksy.szpt;
import cn.hutool.crypto.digest.DigestUtil; import cn.hutool.crypto.digest.DigestUtil;
import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.zksy.szpt.domain.ListImageType;
import com.zksy.szpt.domain.UploadImageDTO;
import com.zksy.szpt.domain.dto.XxRwwcqkDTO; import com.zksy.szpt.domain.dto.XxRwwcqkDTO;
import com.zksy.szpt.service.AppStoreService; import com.zksy.szpt.service.AppStoreService;
import com.zksy.szpt.util.EncryptUtil; import com.zksy.szpt.util.EncryptUtil;
...@@ -15,6 +17,7 @@ import org.springframework.web.reactive.function.client.WebClient; ...@@ -15,6 +17,7 @@ import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono; import reactor.core.publisher.Mono;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.UUID;
/** /**
* A simple unit test * A simple unit test
...@@ -22,7 +25,7 @@ import javax.annotation.Resource; ...@@ -22,7 +25,7 @@ import javax.annotation.Resource;
@SpringBootTest() @SpringBootTest()
public class MainTest { public class MainTest {
String nonce = "2"; String nonce = "10";
String timestampStr = "21"; String timestampStr = "21";
String appId = "1"; String appId = "1";
...@@ -43,7 +46,6 @@ public class MainTest { ...@@ -43,7 +46,6 @@ public class MainTest {
String secretKey = this.appStoreService.getAppSecretByAppKey(appId); String secretKey = this.appStoreService.getAppSecretByAppKey(appId);
Assertions.assertNotNull(secretKey, "appId不存在");//断言appId存在,为空直接抛出异常不进行下一步测试,提高测试效率 Assertions.assertNotNull(secretKey, "appId不存在");//断言appId存在,为空直接抛出异常不进行下一步测试,提高测试效率
// Assertions.fail(secretKey);
//请求参数 //请求参数
XxRwwcqkDTO xxRwwcqkDTO = new XxRwwcqkDTO(); XxRwwcqkDTO xxRwwcqkDTO = new XxRwwcqkDTO();
xxRwwcqkDTO.setRwid("123456"); xxRwwcqkDTO.setRwid("123456");
...@@ -78,4 +80,47 @@ public class MainTest { ...@@ -78,4 +80,47 @@ public class MainTest {
.block(); .block();
System.out.println(response); System.out.println(response);
} }
/**
* 任务完成情况
*/
@Test
@DisplayName("文件上传")
public void uploadFileTest() {
nonce = UUID.randomUUID().toString();
timestampStr = String.valueOf(System.currentTimeMillis() / 1000);
String secretKey = this.appStoreService.getAppSecretByAppKey(appId);
Assertions.assertNotNull(secretKey, "appId不存在");//断言appId存在,为空直接抛出异常不进行下一步测试,提高测试效率
//请求参数
UploadImageDTO uploadImageDTO = new UploadImageDTO();
uploadImageDTO.setImagePath("http://192.168.168.211/guoqing.jpg");
uploadImageDTO.setImageType(ListImageType.FACE);
String json = null;
try {
json = objectMapper.writeValueAsString(uploadImageDTO);
} catch (JsonProcessingException e) {
Assertions.fail("json序列化失败");
}
//请求体加密
json = EncryptUtil.getInstance().AESEncode(json, secretKey);
//签名appId+nonce+timestampStr+aes(body)
String data = String.format("%s%s%s%s", appId, nonce, timestampStr, json);
String generatedSignature = DigestUtil.md5Hex(data);
//请求
WebClient webClient = WebClient.builder()
.baseUrl("http://localhost:8086")
.defaultHeader("Content-Type", "application/json")
.build();
String response = webClient.post().uri("/rest/image/upload")
.header(SignatureUtil.APPID, appId)
.header(SignatureUtil.NONCE, nonce)
.header(SignatureUtil.TIMESTAMP, timestampStr)
.header(SignatureUtil.SIGNATURE, generatedSignature)
.body(Mono.just(uploadImageDTO), XxRwwcqkDTO.class)
.retrieve()
.bodyToMono(String.class)
.block();
System.out.println(response);
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment