花了一天时间,完成了一个上传功能,分享出来,减少坎坷。
HTML代码段:
<img id="imghead" src="原始图片" />
<a class="a-file" href="javascript:void(0)" type="file" data-role="none">+</a>
<input class="hidden" type="file" capture="camera" accept="image/*" id="takePictureField" id="payfile" name="myfile" οnchange="fileChange(this)" data-role="none"></input>
jquery代码段:
function fileChange(this) {
alert();
var filepath = $(this).val();
if (filepath == "") {
return;
}
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length)
.toUpperCase();
if (".jpg|.png|.bmp|.jpeg".toUpperCase().indexOf(
ext.toUpperCase()) == -1) {
alert("只允许上传jpg、png、bmp、jpeg格式的图片");
return false;
}
lrz(that.files[0], {
width : 600
}).then(function(rst) {
$.ajax({
url : "上传路径",
type : "POST",
data : {
imgdata : rst.base64
},
dataType : "json",
cache : false,
async : false,
success : function(data) {
if (data.success) {
alert();
var filepath = $(this).val();
if (filepath == "") {
return;
}
var extStart = filepath.lastIndexOf(".");
var ext = filepath.substring(extStart, filepath.length)
.toUpperCase();
if (".jpg|.png|.bmp|.jpeg".toUpperCase().indexOf(
ext.toUpperCase()) == -1) {
alert("只允许上传jpg、png、bmp、jpeg格式的图片");
return false;
}
lrz(that.files[0], {
width : 600
}).then(function(rst) {
$.ajax({
url : "上传路径",
type : "POST",
data : {
imgdata : rst.base64
},
dataType : "json",
cache : false,
async : false,
success : function(data) {
if (data.success) {
//显示图片
$("#imghead").attr('src', rst.base64);
} else {
alert(data.success);///data.message为上传失败原因
}
},
error : function() {
alert("上传失败");
}
});
});
}
$("#imghead").attr('src', rst.base64);
} else {
alert(data.success);///data.message为上传失败原因
}
},
error : function() {
alert("上传失败");
}
});
});
}
SpringMVC部分代码段:
public ModelMap fileUploadPicture(String imgdata, HttpServletRequest request) {
//。。。
Base64 decoder = new Base64();
FileOutputStream outputStream = null;
// new一个文件对象用来保存图片
File imageFile = new File(path);
if (!imageFile.exists()) {
imageFile.mkdirs();
}
//。。。
Base64 decoder = new Base64();
FileOutputStream outputStream = null;
// new一个文件对象用来保存图片
File imageFile = new File(path);
if (!imageFile.exists()) {
imageFile.mkdirs();
}
//图片在服务器上的路径
imageFile = new File(imgPath);
// 创建输出流
outputStream = new FileOutputStream(imageFile);
// 获得一个图片文件流
imageFile = new File(imgPath);
// 创建输出流
outputStream = new FileOutputStream(imageFile);
// 获得一个图片文件流
byte[] result = decoder.decode(imgdata.split(",")[1]);// 解码
for (int i = 0; i < result.length; ++i) {
if (result[i] < 0) {// 调整异常数据
result[i] += 256;
}
}
outputStream.write(result);
for (int i = 0; i < result.length; ++i) {
if (result[i] < 0) {// 调整异常数据
result[i] += 256;
}
}
outputStream.write(result);