业务需求:
html页面上传图片到后台 ,后台用Java转换成Base64 ,然后把数据存到数据库。
---------------------------------------------------------------------------------------------------------------------
不了解图片与Base64互转的 ,可以看看下面这篇博客
https://www.cnblogs.com/buguge/p/12177895.html
前端
我用的是模态框,使用的是Ajax上传方式
<label class="control-label" for="img">图例:</label>
<input type="file" class="form-control" id="img" placeholder="">
$("#add").click(function() {
var file = $('#img')[0].files[0];
var formData = new FormData();
formData.append("id", "007");
formData.append("name", "007");
formData.append("img", file);
$.ajax({
url: url + 'mibs/zzjgs/getZzjgAdd',
data: formData,
type:'post',
cache: false,
processData: false,
contentType: false,
async : false,
dataType:'json',
success: function (data) {
if ((data.msg) == "成功" ){
alert("操作成功!");
$('#modify').modal('hide');
getSearch();
}else {
alert("操作失败!");
}
}
})
});
后台Springcloud
先看一下项目结构:
feign(网关)
Controller代码:
@RequestMapping(value = "/zzjgs/getZzjgAdd", method = RequestMethod.POST)
@CrossOrigin
public String addzzjg(@RequestParam("id") String id, @RequestParam("name") String name,@RequestParam("img")MultipartFile imgFile) throws UnsupportedEncodingException {
R r_ = new R(0, null, "");
r_ = SysZzjgService.addzzjg(id,name,imgFile);//调用service代码
String strv = JSONObject.toJSONString(r_);
return strv;
}
service代码:
需要一个注解 consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
没有这个注解无法传文件(MultipartFile )到后面的 Cloud
@PostMapping(value = "/addZzjg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
R addzzjg(@RequestParam String id, @RequestParam String name, @RequestPart("img") MultipartFile img);
Cloud
处理图片,操作数据库
先来俩工具类
1.这个就是上面那个链接里的代码
package com.zhongjia.system.util;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;
public class ImageBase64Converter {
/**
* 本地文件(图片、excel等)转换成Base64字符串
*
* @param imgPath
*/
public static String convertFileToBase64(String imgPath) {
byte[] data = null;
// 读取图片字节数组
try {
InputStream in = new FileInputStream(imgPath);
System.out.println("文件大小(字节)="+in.available());
data = new byte[in.available()];
in.read(data);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// 对字节数组进行Base64编码,得到Base64编码的字符串
BASE64Encoder encoder = new BASE64Encoder();
String base64Str = encoder.encode(data);
return base64Str;
}
/**
* 将base64字符串,生成文件
*/
public static File convertBase64ToFile(String fileBase64String, String filePath, String fileName) {
BufferedOutputStream bos = null;
FileOutputStream fos = null;
File file = null;
try {
File dir = new File(filePath);
if (!dir.exists() && dir.isDirectory()) {//判断文件目录是否存在
dir.mkdirs();
}
BASE64Decoder decoder = new BASE64Decoder();
byte[] bfile = decoder.decodeBuffer(fileBase64String);
file = new File(filePath + File.separator + fileName);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
bos.write(bfile);
return file;
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (bos != null) {
try {
bos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
}
2.这个是获取项目根目录的,图片就上传到项目根目录中就OK
package com.zhongjia.system.util;
import java.io.File;
public class UploadUtils {
// 项目根路径下的目录 -- SpringBoot static 目录相当于是根路径下(SpringBoot 默认)
public final static String IMG_PATH_PREFIX = "static/uploadImgs";
public static File getImgDirFile(){
// 构建上传文件的存放 "文件夹" 路径
String fileDirPath = new String("src/main/resources/" + IMG_PATH_PREFIX);
File fileDir = new File(fileDirPath);
if(!fileDir.exists()){
// 递归生成文件夹
fileDir.mkdirs();
}
return fileDir;
}
}
Controller代码:
图片上传到项目根目录(本地)后,开始处理
@PostMapping(value = "/addZzjg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public R getzzjgadd(@RequestParam(value = "zzid",required = true)int zzid, @RequestParam(@RequestParam(value = "id",required = true)String parid,@RequestParam(value = "name",required = true)String remark,@RequestPart(value = "img",required = true) MultipartFile imgFile) throws Exception {
try {
String img64="";
// 拿到文件名
String filename = imgFile.getOriginalFilename();
//拿到文件后缀名
String fileTyle =filename.substring(filename.lastIndexOf(".")+1,filename.length());
// 存放上传图片的文件夹
File fileDir = UploadUtils.getImgDirFile();
// 输出文件夹绝对路径 -- 这里的绝对路径是相当于当前项目的路径而不是“容器”路径
//System.out.println(fileDir.getAbsolutePath());
try {
// 构建真实的文件路径
File newFile = new File(fileDir.getAbsolutePath() + File.separator + filename);
//System.out.println(newFile.getAbsolutePath());
// 上传图片到 -》 “绝对路径”
imgFile.transferTo(newFile);
//图片转换成Base64
String imgBase64Str= ImageBase64Converter.convertFileToBase64(newFile.getAbsolutePath());
//前台直接这样就可以显示 base64类型的图片 <img src=“data:image/png;base64,***********************************"/>
//所以要把数据组合起来 ,fileTyle是后缀名 imgBase64Str是图片转换的Base64
img64 = "data:image/"+fileTyle+";base64,"+imgBase64Str;
//删除存放图片的文件夹 既然base64都存到数据库了 上传的图片就可以删除了
FileUtils.deleteDirectory(fileDir);
} catch (IOException e) {
e.printStackTrace();
}
int m = sysZzjgService.getzzjgedit(id,name,img64);//根据SQL语句修改
return R.result(m, (Object) m, ExceptionCode.SUCCESS.getMsg());
} catch (Exception ex) {
return R.result(ExceptionCode.JSON_PARSE_ERROR.getCode(),(Object)"[{}]",ex.getMessage());
}
}
OK了 剩下的Service 、Mapper的代码就看你们自己的需求来写。
声明:本站所有文章,如无特殊说明或标注,均为网络收集发布。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。