`

关于Struts中Jquery上传组件uploadify用法

阅读更多

1.JS


<script type="text/javascript" src="${ ctx }/widgets/upload/jquery-1.3.2.min.js"></script>
    <script type="text/javascript" src="${ ctx }/widgets/upload/swfobject.js"></script>

    <script type="text/javascript" src="${ ctx }/widgets/upload/jquery.uploadify.v2.1.0.min.js"></script>

<script type="text/javascript">

$(document).ready(function(){
            $("#uploadify").uploadify({
                'uploader'       : '${ ctx }/widgets/upload/uploadify.swf',
                'script'         : '${ ctx }/uploadfile.do?method=upload',
                'scriptData'     : {'type':'clientproduct'},
                'method'         : 'post',
                'cancelImg'      : '${ ctx }/styles/images/delete.gif',
                'buttonImg'        : '${ ctx }/widgets/upload/xzButton.gif',
                'folder'          : '/upload/img',
                'queueID'        : 'fileQueue',
                'auto'           : false,
                'width'             : 90,
                'height'         : 20,
                'sizeLimit'         : 3*1024*1024,
                'multi'          : true,
                'wmode'             : 'transparent',
                'simUploadLimit' : 999,
                'fileExt'         : '*.png;*.doc;*.gif;*.jpg;*.bmp;*.jpeg;*.docx;*.txt;*.pdf',
                'fileDesc'         : '图片文件(*.png;*.doc;*.gif;*.jpg;*.bmp;*.jpeg;*.docx;*.txt;*.pdf)',
                'onSelectOnce' : function(event,data,data)
                {
                  filesSelected:true;
                },
                'onComplete' : function(event,queueId,fileObj,response,data)
                {
                    //alert("response="+response);
                    setImg2product($.trim(response),$('#ttype').val())
                },
                'onAllComplete' : function(event,data)
                {   
                    if($.trim($('#ttype').val())==""){
                        $('#result').html('没有选择添加文件类型,请重新上传!');
                    }else{
                        $('#result').html(data.filesUploaded +'个文件上传成功');
                    }
                } 
            });
           
        });
       
        function shun(){
            if($.trim($('#ttype').val())==""){
                alert("请先选择添加文件类型!");
            }else{
                $('#uploadify').uploadifyUpload();
            }   
        }
       
        function setImg2product(dpID,type){//绑定产品与图片
            var clinentproductID = $("*[name='id']").val();
            $.ajax({
                type : "post",
                method : "post",
                dataType : "json",
                data:{
                    "clinentproductID":clinentproductID,
                    "dpID":dpID,"type":type
                },
                url : "clientdieplate.do?method=saveInfo",
                success : function(data) {
                    showImg(type);
                }
            });
        }
       
        function showImg(type){//显示文件
            var clinentproductID = $("*[name='id']").val();
            $.ajax({
                type : "post",
                method : "post",
                dataType : "json",
                data:{
                    "clinentproductID":clinentproductID,"type":type
                },
                url : "clientdieplate.do?method=getInfoByclientproductID",
                success : function(data) {
                    if($.trim(data.type)=="dieplate"){
                        $('#dieplantShow').html(data.dieplantShow);
                    }else if($.trim(data.type)=="certification"){
                        $('#certificationShow').html(data.certificationShow);
                    }else if($.trim(data.type)=="colorbox"){
                        $('#colorboxShow').html(data.colorboxShow);
                    }else if($.trim(data.type)=="boxmark"){
                        $('#boxmarkShow').html(data.boxmarkShow);
                    }else if($.trim(data.type)=="screwpack"){
                        $('#screwpackShow').html(data.screwpackShow);
                    }else if($.trim(data.type)=="serialno"){
                        $('#serialnoShow').html(data.serialnoShow);
                    }else if($.trim(data.type)=="product"){
                        $('#productShow').html(data.productShow);
                    }else if($.trim(data.type)=="other"){
                        $('#otherShow').html(data.otherShow);
                    }else if($.trim(data.type)=="productinfo"){
                        $('#productinfoShow').html(data.productinfoShow);
                    }else if($.trim(data.type)=="specification"){
                        $('#specificationShow').html(data.specificationShow);
                    }
                }
            });
        }
       
        function fnDeleteDiePlate(fileID,type){//文件删除
            //var text;
            //if(type=="specification" || type=="productinfo"){
            //    text = "您是否要删除该文件?";
            //}else{
            //    text = "您是否要删除该图片?";
            //}
            //if(window.confirm(text)){
            $.ajax({
                type : "post",
                method : "post",
                dataType : "json",
                data:{
                    "dpid":fileID,"type":type
                },
                url : "clientdieplate.do?method=deleteInfo",
                success : function(data) {
                    showImg(data.type);   
                }
            });
            //}
        }
       
        function fnDowmloadFile(fileID){//文件下载
            $.ajax({
                type : "post",
                method : "post",
                dataType : "json",
                data:{
                    "fileID":fileID
                },
                url : "../uploadfile.do?method=downloadFile"
            });
        }
      </script>


2.Action方法

/**
     * Description:文件上传
     * @author 李仕亮
     */
    @SuppressWarnings("unchecked")
    private Map<String,String> uploadFile(LazyValidatorForm uploadfileForm, HttpServletRequest request) throws FileNotFoundException, IOException {
        //检查并创建上传目录
        String filepath = "upload//" + PowerConstant.UPLOAD_IMG_PATH;
        String dirPath = request.getSession().getServletContext().getRealPath("/") + filepath;// 图片上传路径request.getRealPath("/")
        FileOperateUtil.creatDirs(dirPath);
        //取得一个文件
        Hashtable<String, FormFile> fileHashtable = uploadfileForm.getMultipartRequestHandler().getFileElements();
        Enumeration<String> enumeration = fileHashtable.keys();
        enumeration.hasMoreElements();
        String key = (String) enumeration.nextElement();
       
        FormFile formFile = (FormFile)fileHashtable.get(key);
       
        String rename = UUID.randomUUID().toString();//防止命名重复,产生相应的异常
       
        String filename = formFile.getFileName().trim(); //文件名
        String filetype = filename.substring(filename.lastIndexOf(".") + 1);//文件类型
        String realPath = dirPath + "//" + rename + "." + filetype; //真实文件路径
        String contentType = formFile.getContentType();
        String filesize = FileSizeConvert.convert(formFile.getFileSize()); //文件大小

        Map<String,String> fileMap = null;
        if (!filename.equals("")) {
            // 在这里上传文件
            //System.out.println(rename + "." + filetype);
            //System.out.println("---------------------------------------------");
            InputStream is = formFile.getInputStream();
            OutputStream os = new FileOutputStream(realPath);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            is.close();
           
            // 将此文件的信息作为参数预先保存,最后存入数据库中
            fileMap =new HashMap<String,String>();
            fileMap.put("filename", filename);
            fileMap.put("filepath", filepath + "//" + rename + "." + filetype);
            fileMap.put("filetype", contentType);
            fileMap.put("filesize", filesize);
        }
        return fileMap;
    }   
   
    /**
     * Description:文件上传
     * @author 李仕亮
     * @throws MapperException
     */
    @SuppressWarnings("unchecked")
    public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws IOException, ServletException, MapperException  {
        LazyValidatorForm uploadForm = (LazyValidatorForm) form;
        String type = request.getParameter("type");
        //log.info("type="+type);
        Map<String,String> fileMap = uploadFile(uploadForm, request);
       
        if("clientproduct".equals(type)){//上传客户产品相关图片
            if(fileMap!=null){
                response.setContentType("text/html; charset=utf-8");
                Uploadfile file = uploadfileManager.saveUpLoad(fileMap);
                PrintWriter out=response.getWriter();
                out.println(file.getId());
            }
        }else {
            if(fileMap!=null){
                Uploadfile file = uploadfileManager.saveUpLoad(fileMap);
                Map<String, Object> resultJSON = new HashMap<String, Object>();
                resultJSON.put("file", file);
                response.setContentType("text/plain;charset=UTF-8");
                super.renderHtml(response, JSONMapper.toJSON(resultJSON).render(false));
            }
        }
   
        return null;
    }
   
    public PrintWriter encodehead(HttpServletRequest request,HttpServletResponse response) throws IOException{
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html; charset=utf-8");
        return response.getWriter();
    }
   
    /**
     * 文件下载
     */
    @SuppressWarnings("unused")
    public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        // 存入下载记录
        String fileID = request.getParameter("fileID");
        Uploadfile uploadFile = uploadfileManager.get(fileID);
        // 跳转到下载页面
        request.setAttribute("filePath", request.getSession().getServletContext().getRealPath("/") + uploadFile.getPath());
        request.setAttribute("fileName", uploadFile.getName());
        request.setAttribute("contentType", uploadFile.getType());
        return new ActionForward("/download.do");
    }


3. jsp代码

<table style="width: 90%;">
                                                    <tr>
                                                        <td style="width:108px;">
                                                            <select name="ttype" id="ttype" style="height:20px;">
                                                                <option value="">--请选择--</option>
                                                                <c:if test="${productprice.hidecpinfo!=1 }">
                                                                    <option value="product">添加产品图片</option>
                                                                    <option value="certification">添加LOGO和标签图</option>
                                                                    <option value="colorbox">添加彩盒图</option>
                                                                    <option value="screwpack">添加螺丝包及配件图</option>
                                                                    <option value="boxmark">添加外箱唛头图</option>
                                                                    <option value="serialno">添加条形码\序列号图</option>
                                                                    <option value="other">添加其他图片</option>
                                                                    <option value="specification">添加产品说明书</option>
                                                                    <option value="dieplate">添加客户产品刀版</option>
                                                                </c:if>
                                                                <option value="productinfo">添加产品关键数据信息表</option>
                                                            </select>
                                                            <input type="hidden" name="type" id="type" value=""/>
                                                        </td>
                                                        <td style="width: 10px;">
                                                        </td>
                                                        <td style="width: 80px;">
                                                            <input type="file" name="uploadify" id="uploadify" />
                                                        </td>
                                                        <td align="left">
                                                            <a href="javascript:;" onclick="shun();">开始上传</a>|
                                                            <a href="javascript:jQuery('#uploadify').uploadifyClearQueue()">取消上传</a>
                                                        <span id="result" style="font-size: 13px;color: red"></span>
                                                        </td>
                                                    </tr>
                                                </table>       
                                                <div id="fileQueue" style="width: 500px;height: 150px;border: 2px solid green;overflow: scroll"></div>

3
0
分享到:
评论
1 楼 ahy608 2010-09-27  
为什么 我返回的是空的

相关推荐

Global site tag (gtag.js) - Google Analytics