关于uploadify

Jsp

/* 上传商品详细图片 */
        $("#productPic").uploadify({
            'uploader' : '<%=request.getContextPath()%>/js/uploadify/uploadify.swf',
            'script' : '<%=request.getContextPath()%>/ProductImage/ProductImage_upload',//后台处理的请求  
            'cancelImg' : '<%=request.getContextPath()%>/js/uploadify/uploadify-cancel.png',
            'folder' : 'upload',                                                  //您想将文件保存到的路径  
            'fileDataName'   : 'uploadify',                                          //和input的name属性值保持一致就好,Struts2就能处理了
            'queueID' : 'image',                                                //与下面的id对应  
            'method'         :'GET',                                                 //如果要传参数,就必须改为GET 
            'queueSizeLimit' : 1,                                                    //上传6张
            'fileDesc' : '*.jpg,*.png,*.gif,*.JPEG,*.PNG,*.GIF',
            'fileExt' : '*.jpg;*.gif;*.jpeg;*.png;*.bmp',                            //控制可上传文件的扩展名,启用本项时需同时声明fileDesc  
            /*
            'fileDesc' : '*.zip,*.rar',  
            'fileExt' : '*.zip;*.rar',  
             */
            'auto' : true,                                                           //自动上传
            'multi' : false,
            'simUploadLimit' : 1,                                                    //上传个数
            'buttonText' : '浏览',
            //'buttonImg'      :'${ctx}/images/browse2.png',
            'displayData'    : 'speed',                                              //有speed和percentage两种,一个显示速度,一个显示完成百分比 
            //'scriptData'     : {'type':'product'},
            onOpen: function(event, queueID, fileObj) {
                 if(fileObj.size==0){
                        alert("文件 " +fileObj.name +"内容为空取消其上传!");
                        $("#productPic").uploadifyCancel(queueID);
                 }
                 if(fileObj.size / 1024 / 1024 > fileSize){
                        alert("文件 " +fileObj.name +"内容大于"+fileSize+"M,取消其上传!");
                        $("#productPic").uploadifyCancel(queueID); 
                 }
                 if(fileObj.type != '.jpg' &&fileObj.type != '.png' &&fileObj.type != '.gif' 
                         &&fileObj.type != '.JPEG' &&fileObj.type != '.PNG' && fileObj.type != '.GIF'){
                     alert("请您选择jpg、png、gif、JPEG、PNG、GIF格式的文件!");
                     $("#productPic").uploadifyCancel(queueID); 
                 }

            },
            onComplete : function(event,queueID, fileObj, response,data) {
                $("#path").val(response);
                $("#path").siblings("img").attr("src",response);
                $("#pathmng").attr("style","color:black");
                $("#msg").text("");
            }
        });

Java代码:

    private File uploadify;
    public File getUploadify() {
        return uploadify;
    }
    public void setUploadify(File uploadify) {
        this.uploadify = uploadify;
    }

    private String uploadifyFileName;
    public String getUploadifyFileName() {
        return uploadifyFileName;
    }

    public void setUploadifyFileName(String uploadifyFileName) {
        this.uploadifyFileName = uploadifyFileName;
    }

    /**
     * 判上传图片,生成唯一的UUID
     */
    public String upload() throws Exception{
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();
        response.setCharacterEncoding("utf-8");
        // 项目路径
        String path = request.getSession().getServletContext().getRealPath("");       
        // 项目上一级路径
        path = path.substring(0,path.lastIndexOf(File.separator));                    

        String url ="/"+this.getPath("uploads")+"/images/";                  


        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
        url += df.format(date);// 文件夹--日期
        url += "/";


        File f2 = new File(path+url);
        if (!f2.exists()) {
            f2.mkdirs();
        }


        String name = "";
        String extName = "";
        // 获取扩展名
        if (uploadifyFileName.lastIndexOf(".") >= 0) {
            extName = uploadifyFileName.substring(uploadifyFileName.lastIndexOf("."));
        }
        File file = null;
        String image200px="";

        do {
            name = UUID.randomUUID().toString();
            file = new File( path + url + name + extName);
        } while (file.exists());
        CopyFileUtil.copyFile(uploadify.getPath(),file.getPath(), true);   //生成原图
        uploadify.delete();

        String Path200px = "";
        //生成200px的图
        if(extName.equalsIgnoreCase(".jpg") || extName.equalsIgnoreCase(".png") || 
                extName.equalsIgnoreCase(".gif") || extName.equalsIgnoreCase(".JPEG") || 
                extName.equalsIgnoreCase(".PNG") || extName.equalsIgnoreCase(".GIF")){
            String fileS =path + url + name + extName;
            int point = fileS.lastIndexOf(".");

            image200px = fileS.substring(0, point) + "new" + extName;//(列表页搜索结果图)

            FileUtility.generateImageThumb(fileS, image200px, 200, 200);     //利用原图截取200px的图

            File f=new File(fileS);  //删除原图片
            f.delete();

            Path200px=image200px.substring(image200px.indexOf("/"), image200px.length());
        }


        response.getWriter().print(Path200px);
        return null; 
    }


    /**
     * uploadify压缩包上传
     */
    public String fileUpload() throws Exception{
        HttpServletResponse response = ServletActionContext.getResponse();
        HttpServletRequest request = ServletActionContext.getRequest();
        response.setCharacterEncoding("utf-8");
        String path = request.getSession().getServletContext().getRealPath("");      

        path = path.substring(0,path.lastIndexOf(File.separator));                    

        String url ="/"+this.getPath("uploads")+"/images/";                  

        String  savePath = path + url;
        File f1 = new File(savePath);
        if (!f1.exists()) {
            f1.mkdirs();
        }

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        List fileList = null;
        try {
            fileList = upload.parseRequest(request);    //获取到上传的东西
        } catch (FileUploadException ex) {
            ex.printStackTrace();
            System.out.println(1);
            return "";
        }

        Iterator<FileItem> it = fileList.iterator();
        String name = "";
        String extName = "";

        while (it.hasNext()) {
            FileItem item = it.next();
            if (!item.isFormField()) {
                long size = item.getSize();
                String type = item.getContentType();
                name = item.getName();

                if (name == null || name.trim().equals("")) {
                    continue;
                }

                 // 扩展名格式:
                 if (name.lastIndexOf(".") >= 0) {
                     extName = name.substring(name.lastIndexOf("."));
                 }

                 File saveFile = new File(savePath + name);

                 try {
                     item.write(saveFile);
                 } catch (Exception e) {
                     e.printStackTrace();
                 }
            }
        }
        return savePath + name;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值