base64编码 springboot_【Java】【SpringBoot】基于BASE64的图片上传、存储

本文介绍如何在SpringBoot应用中利用Base64编码进行图片上传和存储。前端通过FormData发送文件,后台接收到文件后转换为Base64字符串,存储到数据库的MediumBlob字段中。在展示时,将Base64字符串还原为图片。
摘要由CSDN通过智能技术生成

//保存图片信息

$scope.save = function() {var fd = newFormData();var file = document.getElementById('homeImg').files[0];

fd.append('homeImg', file);$http.post(CommonConfig.RestBaseUrl.CaoBaoService+ 'homeimgs/upload?id=' + $scope.detailInfo.id + '&sortNum=' +$scope.detailInfo.sortNum, fd, CommonConfig.fileUploadReqConfig)

.then(function (result) { //正确请求成功时处理

console.log('save:result', result);if (result.data.code == 'NONE_ERROR') {

$scope.modalContent= '保存成功!';

$('#myModal').modal('show');

$scope.getHomeImgs($scope.detailInfo.id);

$scope.resetDetailInfo();

}else{

$scope.modalContent= '保存失败!';

$('#myModal').modal('show');

}

}).catch(function (result) { //捕捉错误处理

console.log(result);

});

};

请求参数设置:app

CommonConfig.

fileUploadReqConfig = {

headers: {

'Content-Type'

:

undefined },

transformRequest:

angular.

identity

};

前台展现:ide

<

img

src=

"data:image/png;base64,{{viewImgData}}"

width=

"100%"

height=

"100%"

alt=

"没法显示"

/>

后台post

后台Model中用String存储便可。spa

数据库采用MediumBlob类型。code

后台Rest请求处理:orm

import org.apache.commons.codec.binary.Base64;

@PostMapping(value = "/upload")public RestRsp upload(HttpServletRequest request, @RequestParam @Nullable intsortNum, @RequestParam @Nullable String id)

{

RestRsp result = new RestRsp();

HomeImgsMO mo= null;try{

List files = ((MultipartHttpServletRequest) request).getFiles("homeImg");if(StringUtil.isNotEmpty(id))

{

mo=homeImgsBusiness.getById(id);

mo.setSortNum(sortNum);if(CollectionUtil.isNotEmpty(files))

{

mo.setImgData(Base64.encodeBase64String(files.get(0).getBytes())); }

homeImgsBusiness.modify(mo);

}else{if(CollectionUtil.isEmpty(files))

{throw new LittleCatException("upload home img:img is null.");

}

mo= newHomeImgsMO();

mo.setSortNum(sortNum);

mo.setImgData(Base64.encodeBase64String(files.get(0).getBytes()));

result.getData().add(homeImgsBusiness.add(mo));

}

}catch(LittleCatException e)

{

result.setCode(e.getErrorCode());

result.setMessage(e.getMessage());

logger.error(e.getMessage(), e);

}catch(Exception e)

{

result.setCode(Consts.ERROR_CODE_UNKNOW);

result.setMessage(e.getMessage());

logger.error(e.getMessage(), e);

}returnresult;

}

POM:blog

图片

commons-codec

commons-codec

1.11

提交数据库操做:

public static final String CHARSET_NAME = "utf-8";

new SerialBlob(mo.getImgData().getBytes(Consts.CHARSET_NAME))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值