public ActionResult TestUpload(ActionContext ac){
ActionResult ar=new ActionResult();
JSONObject args=ac.getArguments();
String base64 = JsonUtil.getString(args, "base64").substring(23);
String base64len = JsonUtil.getString(args, "base64len");
String basePath = EcpParameter.getAttachmentDirectory();
String storePath = ((DateFormat) formats.get(EcpParameter.getAttachmentStoreType()))
.format(new Date());
UUID name = UUID.randomUUID();
String storeName = name + "."+"jpeg";
String absoluteName = FileUtil.joinPath(new String[] { basePath, storePath, storeName });
GenerateImage(base64,absoluteName);
PictureModel picture = new PictureModel();
picture.setId(name);
picture.setName(storeName);
picture.setStorePath(storePath);
picture.setStoreName(storeName);
picture.setUploadUserId(ac.getUserId());
picture.setUploadTime(new Date());
//picture.setSize((int) fileItem.getSize());
UUIDpictureId=PictureHome.getDao().insert(picture);
ar.putClientValue("pictureId", pictureId);
if(pictureId!=null){
ar.putClientValue("error", 0);
ar.putClientValue("url", PictureHome.getPictureUrl(pictureId.toString()));
}else{
ar.putClientValue("error", 1);
ar.putClientValue("message", "upload error");
}
if(ac.getResponse()!=null){
ac.getResponse().setContentType("text/html;charset=UTF-8");//application/json
}
ar.putClientValue("success", true);
return ar;
}
public static boolean GenerateImage(String imgStr, String imgFilePath) {// 对字节数组字符串进行Base64解码并生成图片
if (imgStr == null) // 图像数据为空
return false;
BASE64Decoder decoder = new BASE64Decoder();
try {
// Base64解码
byte[] bytes = decoder.decodeBuffer(imgStr);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
return true;
} catch (Exception e) {
return false;
}
}
}