一般上传图片的方式我们都是在前端使用 input file控件来选择文件,后台使用MultipartFile
进行接收,但有的时候会获取到一些其他类型的图片比如base64格式的图片,一般会以
data:image/jpeg;base64,开头,下面进入正题我会说明两种处理方式
<--选择文件-->
<input accept="image/*" type="file" name="img">
<script type="text/javascript">
$("#inputGroupFile01").change(function () {
var file = $("#element_id");
var data = new FormData();
var image = file.get(0).files[0];
data.append("img", image);
$.ajax({
url: “your request url”,
type: "post",
data: data,
async: false,
dataType: "JSON",
processData: false,
contentType: false,
success: function (data) {
// 后台数据回显链接
$("#coverUrl").val(data.url);
}
});
});
</script>
FileController
@Controller
@RequestMapping("/file")
public class FileController {
Logger logger = LoggerFactory.getLogger(FileController.class);
@PostMapping("/uploadImage")
@ResponseBody
public EditorResult uploadFileByEditormd(@RequestParam(name = "img", required = true) MultipartFile file) throws IOException, URISyntaxException {
/** 返回前端数据 */
EditorResult result = new EditorResult();
if(null == file){
return result.fail("文件不存在");
}
String filename = file.getOriginalFilename();
//trim作用是去掉两端的空格
if("".equals(filename.trim())){
return result.fail("文件出现异常");
}
//转换为File类型
File newFile = FileUtil.multipartFileToFile(file);
//写你的处理
//删除项目内缓存文件
if (newFile.exists()) {
newFile.delete();
}
return result.okAndSetUrl(fileUrl);
}
}
Fileutil
public class FileUtil {
static Logger logger = LoggerFactory.getLogger(FileUtil.class);
public static File multipartFileToFile(MultipartFile file) {
try {
String filename = file.getOriginalFilename();
//fileName为图片路径在此处创建默认为项目根目录
File newFile = new File(filename);
//创建一个文件流
FileOutputStream os = new FileOutputStream(newFile);
//把提交的文件通过字节流的方式转成file
os.write(file.getBytes());
//关闭流
os.close();
file.transferTo(newFile);
return newFile;
} catch (Exception e) {
logger.warn(e.getMessage());
}
return null;
}
}
这里我的处理方式是使用获取到的base64图片字符串传到后台进行转码
//src 为base64图片字符串
function imagesAjax(src) {
var data = new FormData();
data.append("img", src);
$.ajax({
url: "/user/alterHeadPortrait",
type: "post",
data: data,
async: false,
dataType: "JSON",
processData: false,
contentType: false,
success: function (data) {
if (data.code == 1) {
alert("修改成功");
}
}
});
}
UserController控制器
@PostMapping("/alterHeadPortrait")
@ResponseBody
public ApiResult alterHeadPortrait(HttpServletRequest req, @RequestParam(name = "img", required = true) String base64Str) {
ApiResult apiResult = new ApiResult();
String filePath = null;
try {
//base64转图片
filePath = base64ImageUtil.GenerateImage(base64Str);
} catch (Exception e) {
logger.info(e.getMessage());
}
//写你的处理上传至本地或oss
File newFile = new File(filePath);
//String fileUrl = new HuaweiObsUtil().upload(newFile);
newFile.delete();//删除暂存文件
User user = ShiroUtils.getSysUser();
user.setHeadPortraitUrl(fileUrl);
//入库更新头像
userService.getDao().getRepository().save(user);
return apiResult.ok("头像修改成功");
}
base64字符串转化成图片,需要将base64字符串数据的前缀给去掉 例如:
data:image/jpeg;base64, 此前缀是作为说明的一个字段 表示文件格式 类型,解码时需要将前缀去掉否则获得到的文件可能会是无法查看的
@Component
public class Base64ImageUtil {
//配置文件中配置
@Value("${spring.servlet.multipart.location}")
private String uploadPath;//此处路径为 D:/upload/
/**
* base64字符串转化成图片
*
* @param imgData 图片编码
* @return * @throws IOException
*/
@SuppressWarnings("finally")//去除警告提示
public String GenerateImage(String imgData) throws IOException { // 对字节数组字符串进行Base64解码并生成图片
if (imgData == null) // 图像数据为空
throw new IllegalArgumentException("图像数据为空");
//以逗号分割,保留后面部分
imgData = imgData.split(",")[1];
OutputStream out = null;
String filePath = null;
try {
BASE64Decoder decoder = new BASE64Decoder();
//拼接地址
filePath = uploadPath + randomName() + ".jpg";
out = new FileOutputStream(filePath);
// Base64解码
byte[] b = decoder.decodeBuffer(imgData);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {// 调整异常数据
b[i] += 256;
}
}
out.write(b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
out.flush();
out.close();
return filePath;
}
}
/***
* 随机生成文件名
* @return
*/
public String randomName() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
Random r = new Random();
StringBuilder tempName = new StringBuilder();
tempName.append(sdf.format(new Date())).append(r.nextInt(100));
return tempName.toString();
}
}
@PostMapping("/checkImg")
@ResponseBody
public ApiResult findImg() {
//根据图片路径获取base64编码
String base64Code = Base64ImageUtil.GetImageStr(imgPath);
return apiResult.ok("查询成功").inject(base64Code);
}
/**
* 图片转化成base64字符串
*
* @param imgFile //文件路径
* @return
*/
public static String GetImageStr(String imgFile) {// 将图片文件转化为字节数组字符串,并对其进行Base64编码处理
logger.info("图片路径: " + imgFile);
InputStream in = null;
byte[] data = null;
String encode = null; // 返回Base64编码过的字节数组字符串
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
try {
// 读取图片字节数组
in = new FileInputStream(imgFile);
data = new byte[in.available()];
in.read(data);
encode = encoder.encode(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return encode;
}
$(function () {
$("#checkForm").on("submit", function (ev) {
//阻止submit表单提交
ev.preventDefault();
$.ajax({
type: 'post',//方法类型
url: '/checkImg',
//data这里根据你自己的条件
data: $("#checkForm").serialize(),
dataType: "json",
success: function (result) {
if (result.code == 1) {
alert(result.msg);
setImage(result.data);
} else {
alert(result.msg);
$("#showImg").hide();
}
},
error: function (data) {
alert(data.msg);
}
});
})
})
function setImage(data) {
//图片前缀
var head = "data:image/jpeg;base64,";
$("#showImg").show();
$("#showImg").find("img").attr("src", head + data);
}