记录一下在做一个报修功能的心路历程,需求功能很简单,一个表单提交,表单包含简单的文字字段以及图片
因为使用的是weui框架,前面的话去找weui的表单和图片上传组件,说实话,weui的组件写的还不错,作为一个不太懂前端的渣渣可以拿来开箱即用
主要是不用调那么多的样式问题,直接上代码:
图片上传
uploadbase64Image(@RequestBody Map
map) throws ParseException, IOException {
Map imageMap = new HashMap<>();
String base64 = map.get("base64").toString();
MultipartFile file = base64DecodedMultipartFile.base64ToMultipart(base64);
//获取文件保存路径
String fileSavePath = globalConfService.getByKey(StaticConfigUtil.FILE_SAVE_PATH).getConfValue();
String fileServerPath = globalConfService.getByKey(StaticConfigUtil.FILE_SERVER_PATH).getConfValue();
fileSavePath = fileSavePath + DateUtil.formatDatetime("yyyy-MM-dd");
fileServerPath = fileServerPath + DateUtil.formatDatetime("yyyy-MM-dd");
if (!file.isEmpty()) {
String fileName = file.getOriginalFilename();
String ext=fileName.substring(fileName.lastIndexOf(".")+1);
String imgName = "/"+UUID.randomUUID()+ "." +ext;
InputStream in = null;
OutputStream out = null;
try {
File serverFile = new File(fileSavePath+imgName);
//判断文件父目录是否存在
if(!serverFile.getParentFile().exists()){
serverFile.getParentFile().mkdir();
}
if (!serverFile.exists()) {
serverFile.createNewFile();
}
in = file.getInputStream();
out = new FileOutputStream(serverFile);
byte[] b = new byte[1024];
int len = 0;
while ((len = in.read(b))!=-1) {
out.write(b, 0, len);
}
out.close();
in.close();
String serverPath = fileServerPath + imgName;
return ResultUtil.successJson(serverPath);
} catch (Exception e) {
e.printStackTrace();
return ResultUtil.errorJson(ErrorEnum.E_40001,e.getMessage());
} finally {
if (out != null) {
out.close();
out = null;
}
if (in != null) {
in.close();
in = null;
}
}
} else {
return ResultUtil.errorJson(ErrorEnum.E_90007);
}
}
public static MultipartFile base64ToMultipart(String base64) {
try {
String[] baseStrs = base64.split(",");
base64Decoder decoder = new base64Decoder();
byte[] b = new byte[0];
b = decoder.decodeBuffer(baseStrs[1]);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
b[i] += 256;
}
}
return new base64DecodedMultipartFile(b, baseStrs[0]);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
总结
到此这篇关于weui上传多图片,压缩,base64编码的示例代码的文章就介绍到这了,更多相关Weui多图片压缩上传内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!