前台
上传控件:
<input type="file" class="custom-file-input" id="
homeImg" name='homeImg'/>
JS提交:
//保存图片信息
$scope.save = function () {
var fd = new FormData();
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);
});
};
请求参数设置:
CommonConfig.
fileUploadReqConfig = {
headers: {
'Content-Type'
:
undefined },
transformRequest:
angular.
identity
};
前台展示:
<
img
src=
"data:image/png;base64,{{viewImgData}}"
width=
"100%"
height=
"100%"
alt=
"无法显示"
/>
后台
后台Model中用String存储即可。
数据库采用MediumBlob类型。
后台Rest请求处理:
import org.apache.commons.codec.binary.Base64;
@PostMapping(value = "/upload")
public RestRsp<String> upload(HttpServletRequest request, @RequestParam @Nullable int sortNum, @RequestParam @Nullable String id)
{
RestRsp<String> result = new RestRsp<String>();
HomeImgsMO mo = null;
try
{
List<MultipartFile> 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 = new HomeImgsMO();
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);
}
return result;
}
POM:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.11</version>
</dependency>
提交数据库操作:
public static final String CHARSET_NAME = "utf-8";
new SerialBlob(mo.getImgData().getBytes(Consts.CHARSET_NAME))
来源:oschina
链接:https://my.oschina.net/u/4255371/blog/3750634