2017-12-15 20:17
可以获取的,base64前台js传过来有个特殊的标识,比较麻烦,以前搞过,发个码给你看看吧,
1、控制层:
public void add() {
String method = getRequest().getMethod();
if ("GET".equals(method)) {
setAttr("tab", getPara("tab"));
setAttr("labelList", labelService.list());
setAttr("categoryList", categoryService.list());
render("add.html");
} else if ("POST".equals(method)) {
try {
Product product = getBean(Product.class, "", true);
String imageFile = getPara("imagefile");
String[] imageFils = imageFile.split("\\*");
String[] imageExt = getParaValues("filetext");
for (String ss : imageFils) {
System.out.println("test=" + ss);
}
Base64Util.createDir(distPath);//在保存前处理下图片目录是否创建,如果未创建就执行创建操作
List imageList = new ArrayList<>();//回调获取保存图片文件
Base64Util.replaceBase64Image(getSellerId(), imageFils, distPath, distPath, imageList);
if (productService.add(getSeller(), product, imageList)) {
renderAjaxResultForSuccessToRedirectUrl(_SUCCESS, url);
return;
}
renderAjaxResultForError(_ERROR);
} catch (Exception e) {
renderAjaxResultForError(_ERROR);
}
}
}
2、Base64util
(1)、 /**
* 创建目录
*/
public static boolean createDir(String fileDir) {
File file = new File(fileDir);
if (!file.exists()) {
return file.mkdirs(); // 如果目录不存在则创建
}
return false;
}
(2)、 /**
* 替换html中的base64图片数据为实际图片
* @param html
* @param fileRoot 本地路径
* @param serRoot 服务器路径
* @return
*/
public static String replaceBase64Image(Integer sellerId, String html[],String fileRoot,String serRoot, List imageList){
File file = new File(fileRoot);
if(!file.exists()){//文件根目录不存在时创建
new File(fileRoot).mkdirs();
}
String htmlContent = "";
for (String hh : html) {
htmlContent = hh;
Pattern pattern = Pattern.compile("\\]*src=\"data:image/[^>]*>");
// pattern = Pattern.compile("/^data:image\\/(jpeg|png|gif);base64,/");
pattern = Pattern.compile("^data:image/(png|gif|jpg|jpeg|bmp|tif|psd|ICO);base64,.*");
Matcher matcher = pattern.matcher(hh);
while (matcher.find()) { //找出base64图片元素
String str = matcher.group();
// String src = sl.substringBetween(str, "src=\"", "\"");//src="..."
String ext = sl.sBlank(sl.substringBetween(str, "data:image/", ";"), "jpg");//图片后缀
// String base64ImgData = sl.substringBetween(str, "base64,", "\"");//图片数据
// String base64ImgData = sl.substringBetween(str, "base64,", "*");//图片数据
String base64ImgData = sl.substringBetween(str, "base64,");//图片数据
if (!sl.isEmpty(ext) && !sl.isEmpty(base64ImgData)) {
//data:image/gif;base64,base64编码的gif图片数据
//data:image/png;base64,base64编码的png图片数据
if ("jpeg".equalsIgnoreCase(ext)) {//data:image/jpeg;base64,base64编码的jpeg图片数据
ext = "jpg";
} else if ("x-icon".equalsIgnoreCase(ext)) {//data:image/x-icon;base64,base64编码的icon图片数据
ext = "ico";
}
String fileName = generateFileName(sellerId, ext); //待存储的文件名
String filePath = fileRoot + File.separator + fileName;//图片路径
try {
boolean fn = convertBase64DataToImage(base64ImgData, filePath);//转成文件
if (fn) {
imageList.add("/" + sellerId + "/" + fileName);
if (sl.isEmpty(imageList) || imageList.size() == 0) {
throw new Exception();
}
}
// String serPath = serRoot + fileName;//服务器地址
// htmlContent = htmlContent.replace(src, serPath);//替换src为服务器地址
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return htmlContent;
}
2017-12-15 20:08
另外,js
//提交(-兼容ie8上传必须使用jquery.form[3.51.0-2014.06.20] 的ajaxSubmit
$(".downs").click(function(){
$("#form1").ajaxSubmit({
type: "post",
url: "/admin/expense/add?xx=#(xx)&_url=#(_url)",
beforeSerialize:function() { //序列化提交数据之前的回调函数
},
beforeSubmit: function (d, f, o) { //提交成功后执行的回调函数
},
success: function (ret) {
if (ret.errorCode == 0) {
location.href="/admin/expense" + suffer;
} else if(ret.errorCode == 1){
Toast.error(ret.message);
} else {
location.href = "/admin/expense" + suffer;
}
},
clearForm:true,
restForm:true
});
return false;//想要阻止自动提交,必须return false;
});
2017-12-15 20:07
你用了ajaxForm做上传,给个例子你参考下或许有得水一轮:
1、 controler层
public void add(){
String method = getRequest().getMethod();
if ("GET".equals(method)) {
Long id = getParaToLong(0);
Expense expense = expenseService.byId(id);
setAttr("expense", expense);
List categoryList = expenseCategoryService.list();
setAttr("categoryList", categoryList);
render("add.html");
} else if ("POST".equals(method)) {
List attachmentList = null;
try {
String basePath = PathKit.getWebRootPath() + "/upload";
String uploadPath = "/expense/attachment/" + DateTimeUtil.nowDate() + "/";
FileUtil.createDirectory(basePath + uploadPath);
attachmentList = getFiles(uploadPath, Cons.Size.MAX_POST_SIZE, "utf-8");
Expense expense = getBean(Expense.class, "", true);
expense.setUserId(getUserId());
expense.put("attachmentList", attachmentList);
Map res = new HashMap<>();
Long id = (Long) res.get("id");
boolean fn = expenseService.add(expense, res);
if (!fn) {
renderError();
return;
}
renderOk(id);
}catch(com.jfinal.upload.ExceededSizeException ex) {
renderJson("state", "上传图片只允许 200K 大小");
} catch(Exception e) {
if (attachmentList != null) {
for (UploadFile uploadFile : attachmentList) {
uploadFile.getFile().delete();
}
}
}
}
}
FileUtil.createDirectory()如果没有相关目录就创建个目录
/**
* 创建目录
* @param descDirName 目录名,包含路径
* @return 如果创建成功,则返回true,否则返回false
*/
public static boolean createDirectory(String descDirName) {
String descDirNames = descDirName;
if (!descDirNames.endsWith(File.separator)) {
descDirNames = descDirNames + File.separator;
}
File descDir = new File(descDirNames);
if (descDir.exists()) {
logger.debug("目录 " + descDirNames + " 已存在!");
return false;
}
// 创建目录
if (descDir.mkdirs()) {
logger.debug("目录 " + descDirNames + " 创建成功!");
return true;
} else {
logger.debug("目录 " + descDirNames + " 创建失败!");
return false;
}
}
2、 service
public boolean add(Expense expense, Map res) {
return Db.tx(()->{
expense.setClickCount(0);//浏览次数,初始为0
expense.setStatus(0);//发布状态:0未发布;1已经发布
expense.setActive(1);//用效标识:0无效;1有效;
if (sl.isEmpty(expense.getCreated())) {//如果创建时间为空,初始化为当前时间
expense.setCreated(new Date());
}
boolean fn = expense.save();
if (!fn) {
return fn;
}
res.put("id", expense.getId());
//保存附件映射记录
try {
fn = uploadFile(expense.get("attachmentList"), expense.getId());
} catch (IOException e) {
e.printStackTrace();
}
if (!fn) {
return fn;
}
return fn;
});
}
private boolean uploadFile(List attachmentList, Long expenseId) throws IOException {
boolean fn = false;
if (sl.isEmpty(attachmentList)) {
fn = true;
return fn;
}
//保存附件映射记录
for (UploadFile attr : attachmentList) {
ExpenseAttachment attachment = new ExpenseAttachment();
attachment.setDownloadCount(0);
attachment.setExpenseId(expenseId);
File srcFile = attr.getFile();
// attachment.setFileSize(attr.get);
String fileName = srcFile.getName();
String ext = fileName.substring(fileName.lastIndexOf("."));
if(".doc".equals(ext) || ".docx".equals(ext) || ".odt".equals(ext)) {//word
attachment.setFileType("word文档");
} else if (".xls".equals(ext) || ".xlsx".equals(ext) || ".ods".equals(ext) || "".equals(ext)) { //excel
attachment.setFileType("excel表格");
} else if (".ppt".equals(ext) || ".pptx".equals(ext) || ".odp".equals(ext)) {
attachment.setFileType("ppt演示文档");
} else if (".jpg".equals(ext) || ".jpeg".equals(ext) || ".png".equals(ext) || ".bmp".equals(ext)) { //price
attachment.setFileType("图片");
} else if (".txt".equals(ext)) {
attachment.setFileType("文本");
} else {
attachment.setFileType("未知");
}
if (!sl.isEmpty(fileName)){
fileName = fileName.substring(0, fileName.lastIndexOf("."));
attachment.setName(fileName);
}
//以注解是处理文件重命名
String path = attr.getUploadPath();
attachment.setPath(path);
fileName = null;
fileName = srcFile.getName(); //UUID.randomUUID().toString() + srcFile.getName().substring(srcFile.getName().lastIndexOf("."));
attachment.setFileName(fileName);
attachment.setCreated(new Date());
File saveFile = new File(PathKit.getWebRootPath() + path + fileName);
fn = saveFile.createNewFile();
if (!fn) {
return fn;
}
FileUtil.copyFile(srcFile, saveFile);
fn = attachment.save();
if (!fn) {
return fn;
}
}
return fn;
}
2017-12-15 19:51
找对阵容了,欢迎光临,我来告诉你,做下判断,贴码给你:
1、requestUtils代码:
public static boolean isIEBrowser(HttpServletRequest request) {
String ua = request.getHeader("User-Agent");
if (ua == null) {
return false;
}
ua = ua.toLowerCase();
if (ua.indexOf("msie") > 0) {
return true;
}
if (ua.indexOf("gecko") > 0 && ua.indexOf("rv:11") > 0) {
return true;
}
return false;
}
2、控制层如:BaseController
public class BaseController extends Controller {
public boolean isIEBrowser() {
return RequestUtil.isIEBrowser(getRequest());
}
public void render(String message, Integer errorCode, Object data) {
Result ret = new Result();
ret.setMessage(message);
ret.setErrorCode(errorCode);
ret.setData(data);
if (isIEBrowser()) {
render(new JsonRender(ret).forIE());
} else {
renderJson(ret);
}
}
2017-11-29 13:05
@三晋一枝花 有问题在官网社区或osc上提到的问题都是得到同等回复与解答的,这就是两结合与兼顾,不能因为具乐部的存在,而造成的误导,感谢你的支持,同时希望更多的人参与JFinal社区的发展,大家一起做些力所能及的事,JFinal联盟离得就不远啦!