|
楼主 |
发表于 2016-12-22 18:41:25
|
显示全部楼层
后台:
package com.grid.util;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.common.CommonFilePath;
import sun.misc.BASE64Decoder;
/**
* 上传图片。
*/
public class UploadImageAjax extends HttpServlet {
boolean success = false;
String savePath = "";
private static final long serialVersionUID = 1L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String loadpath = null;
String name = null;
String imgpath = "";
String image = req.getParameter("image");
String userid = req.getParameter("userid");
// String userid = "22";
// 只允许jpg
String header = "data:image/jpeg;base64,";
if (image.indexOf(header) != 0) {
// ResponseUtils.renderJson(resp, savePath);
return;
}
image = image.substring(header.length());
BASE64Decoder decoder = new BASE64Decoder();
try {
byte[] decodedBytes = decoder.decodeBuffer(image);
// request.getSession().getServletContext().getRealPath("/");
loadpath = CommonFilePath.getInstance().findServerPath();
SimpleDateFormat df1 = new SimpleDateFormat("yyyyMMdd");
String spath = df1.format(new Date());
loadpath = loadpath + "upload\\" + StringUtil.parseInt(userid, 0)
+ "\\" + spath;
System.out.println(loadpath);
name = (new Date()).getTime() + ".jpg";
File outfile = new File(loadpath);
// 如果文件不存在,则创建一个新文件
if (!outfile.exists()) {
outfile.mkdirs();
}
imgpath = "/upload/"
+ StringUtil.parseInt(req.getParameter("userid"), 0) + "/"
+ spath;
FileOutputStream out = new FileOutputStream(loadpath + "/" + name);
out.write(decodedBytes);
out.close();
success = true;
} catch (Exception e) {
success = false;
e.printStackTrace();
}
resp.setContentType("application/json;charset=UTF-8");
resp.setHeader("Pragma", "No-cache");
resp.setHeader("Cache-Control", "no-cache");
resp.setHeader("Access-Control-Allow-Origin", "*");
resp.setDateHeader("Expires", 0);
resp.getWriter().write(imgpath + "/" + name + "|" + name);
}
}
前台:
function callCamera() {
function onSuccess(imageData) {
// alert(imageData);
showResultLine(imageData);
}
function onFail(message) {
alert("失败:" + message);
}
navigator.camera.getPicture(onSuccess, onFail, {
// destinationType : 1,//获取地址
destinationType : navigator.camera.DestinationType.DATA_URL,// 获取base64
quality : 100,
targetWidth : 1500,
targetHeight : 1500,
saveToPhotoAlbum : true
});
}
function uploadImage(img, id) {
//alert(img);
if (img == '') {
//alert(img);
return;
}
$.ajax({
type : 'POST',
url : main_url + '/ajax/uploadimage',
data : {
image : img,
userid : id
},
async : false,
dataType : 'text',
success : function(data) {
imgpaths += data + "#";
// alert(data);
},
error : function(err) {
alert('网络故障');
console.log(err);
}
});
} |
|