Struts2框架下使用Kindeditor上传图片

之前的项目是用Spring的模式上传Kindeditor图片到服务器,但是现在这个项目里面只有Struts2框架所以跟Spring不一样,以下为代码:

public Object fileUpload(){
		String savePath=this.getCurSession().getServletContext().getRealPath("")+"/attached";
        //文件保存路径
        String saveUrl=this.getCurSession().getServletContext().getRealPath("")+"/attached/images/";
        HttpServletResponse response=ServletActionContext.getResponse();
        PrintWriter out = null; //输出流 
        try {  
            out = response.getWriter();  
        } catch (IOException e1) {  
            e1.printStackTrace();  
        }  
        //定义能上传的文件格式
        HashMap<String, String> extMap=new HashMap<String, String>();
        extMap.put("image", "gif,jpg,jpeg,png,bmp");
        extMap.put("flash", "swf,flv");  
        extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");  
        extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,xml,txt,zip,rar,gz,bz2"); 
        //最大的文件大小
        long maxSize = 1000000;
        response.setContentType("text/html; charset=UTF-8");
        if(!ServletFileUpload.isMultipartContent(this.getCurRequest())){
        	return getError("请选择文件");
        }
        File uploadDir=new File(savePath);
        if(!uploadDir.isDirectory()){
        	uploadDir.mkdirs();
        	//return getError("上传目录不存在");
        }
        if(!uploadDir.canWrite()){
        	return getError("没有权利");
        }
        String dirName=this.getCurRequest().getParameter("dir");
        if(dirName==null){
        	dirName="image";
        }
        if(!extMap.containsKey(dirName)){
        	return getError("目录名不正确");
        }
        savePath+=dirName+"/";
        saveUrl+=dirName+"/";
        File saveDirFile=new File(savePath);
        if(!saveDirFile.exists()){
        	saveDirFile.mkdirs();
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd");
        String ymd=sdf.format(new Date());
        savePath+=ymd+"/";
        saveUrl+=ymd+"/";
        File dirFile=new File(savePath);
        if(!dirFile.exists()){
        	dirFile.mkdirs();
        }
        FileItemFactory factory=new DiskFileItemFactory();
        ServletFileUpload upload=new ServletFileUpload(factory);
        upload.setHeaderEncoding("UTF-8");
        MultiPartRequestWrapper  wrapper = (MultiPartRequestWrapper) this.getCurRequest();
        String fileName=wrapper.getFileNames("imgFile")[0];
        File file=wrapper.getFiles("imgFile")[0];
        String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();  
        if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {  
            out.println(getError("上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName)  
                    + "格式。"));  
            return null;  
        }
        if(file.length()>maxSize){
        	out.print(getError("上传文件大小超过限制"));
        	return null;
        }
        String newImgName = sdf.format(new Date()) + "_"  
                + new Random().nextInt(1000) + "." + fileExt;  
        byte[] buffer = new byte[1024];
        FileOutputStream fos;  
        // 获取内存中当前文件输入流  
        InputStream in;  
        try {  
            fos = new FileOutputStream(savePath + "/" + newImgName);  
            in = new FileInputStream(file);  
            int num = 0;  
            while ((num = in.read(buffer)) > 0) {  
                fos.write(buffer, 0, num);  
            }  
            in.close();  
            fos.close();  
        } catch (FileNotFoundException e1) {  
            e1.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } 
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();  
        obj.put("error", 0);  
        obj.put("url", saveUrl + "/" + newImgName);  
        out.println(obj.toJSONString());  
        return null;  
	}

/**
	 * kindeditor错误报告
	 * @param message 错误原因
	 * @return
	 */
	private String getError(String message) {  
        com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();  
        obj.put("error", 1);  
        obj.put("message", message);  
        return obj.toJSONString();  
    } 


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值