ssm mysql 图片存取_ssm框架上传图片保存到本地和数据库示例

本文介绍了ssm框架上传图片保存到本地和数据库示例,主要使用了Spring+SpringMVC+MyBatis框架,实现了ssm框架上传图片的实例,具体如下:

1、前台部分

Title

var image = '';

function selectImage(file){

if(!file.files || !file.files[0]){

return;

}

var reader = new FileReader();

reader.onload = function(evt){

document.getElementById('image').src = evt.target.result;

image = evt.target.result;

}

reader.readAsDataURL(file.files[0]);

}

function uploadImage(){

image = JSON.stringify(image)

$.ajax({

type:'POST',

url: '/blog/test',

data: {base64: image

},

async: false,

dataType: 'json',

success: function(data){

alert(data.success)

if(data.success){

alert('上传成功');

}else{

alert('上传失败');

}

},

error: function(err){

alert('网络故障');

}

});

}

2、controller

@Inject

private IUserService userService;

@RequestMapping(value="test")

@ResponseBody

public ConsoleResult test(String base64){

// 自定义返回前台数据格式

ConsoleResult res = new ConsoleResult();

// 去掉base64数据头部data:image/png;base64,和尾部的” " “

String[] ww= base64.split(",");

base64 = ww[1];

String[] aa = base64.split("\"");

base64 = aa[0];

try {

// 将图片插入数据库

userService.base64test(base64);

// 图片保存到本地

String path = "D:/asdfasdf.jpg";

Base64File file = new Base64File();

file.decoderBase64File(base64, path);

// 成功标识

res.setStatus(ConsoleResult.successStatus);

} catch (Exception e) {

res.setStatus(ConsoleResult.faultStatus);

}

return res;

}

3、base64

/**

* 将base64字符解码保存文件

*

* @param base64Code

* @param targetPath

* @throws Exception

*/

public static void decoderBase64File(String base64Code, String targetPath) {

byte[] buffer;

FileOutputStream out = null;

try {

buffer = new BASE64Decoder().decodeBuffer(base64Code);

out = new FileOutputStream(targetPath);

out.write(buffer);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (out != null) {

out.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

}

4、mapper.xml

update t_user set U_ABOUT = #{base64} where u_name = '971171444'

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值