@PostConstruct
public void init()
{
//发布端口 8000
InetSocketAddress address = new InetSocketAddress(8000);
try {
HttpServer httpServer = HttpServer.create(address, 1);
httpServer.createContext("/", (context)->{
//文件存储路径-----D:/important/images/
String filePath = "D:/important/images/"+context.getRequestURI().toString();
byte[] bytes = Files.readAllBytes(Paths.get(filePath));
context.sendResponseHeaders(200,bytes.length);
context.getResponseHeaders().add("content-type","image/*");
context.getResponseBody().write(bytes);
context.close();
});
httpServer.start();
} catch (IOException e) {
}
}
private static final String BASEPATH = "http://localhost:8000/";
private static final String REALBASEPATH = "D:/important/images/";
public String saveGoods(AddGoodsInfoRequest request) {
GoodsInfo target = new GoodsInfo();
BeanUtils.copyProperties(request, target);
target.setGoodsType(String.join(",", request.getGoodsType()));
Set<String> fileNameSet = Sets.newHashSet();
long l = System.currentTimeMillis();
if (!CollectionUtils.isEmpty(request.getFiles())) {
for (MultipartFile file : request.getFiles()) {
String originName = l + "_" + file.getOriginalFilename();
fileNameSet.add(BASEPATH + originName);
writeImgToUpload(file, REALBASEPATH + originName);
}
}
target.setFileName(String.join(",", fileNameSet));
target.setMainImageUrl(BASEPATH + l + "_" + target.getMainImageUrl());
Date createTime = new Date();
target.setCreateTime(createTime);
target.setUpdateTime(createTime);
goodsInfoMapper.insert(target);
return null;
}
/**
* 文件上传
*/
private String writeImgToUpload(MultipartFile img, String filePath) {
File toFile = new File(filePath);
if (!toFile.getParentFile().exists()) {
toFile.mkdirs();
}
try {
img.transferTo(toFile);
return filePath;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}