• struts1 & jquery form 文件异步上传


    1.概述

    还在用struts1?是的,在地球的没写地方,落后的生产方式还在运转(老项目).

    从 继承org.apache.struts.action.Action, 继承org.apache.struts.action.ActionForm开始吧

    2. 代码

    2.1 html页面

    <html>
    <head>
    <title>网页上传</title>
    </head>
    <body>
        <center>
            <h1>本地文件网页上传</h1>
            <hr>
    
        </center>
    
        <h1>文件信息列表</h1>
        <hr>
        <form  id="myform" method="post" enctype="multipart/form-data">
            <table width="0" border="0" cellspacing="10" cellpadding="0">
            
                <tr>
                    <td>选择文件:</td>
                    <td><input type="file" name="uploadFile" /></td>
                </tr>
                <tr>
                    <td>标题:</td>
                    <td><input type="text" name="filetitle" /></td>
                </tr>
    
                <tr>
                    <td colspan="2">
                        <input type="button" id="mysubmit" value="确认上传"/>
                    </td>
                </tr>
    
            </table>
        </form>
        <script src="script/jquery.js"></script>
        <script src="script/jquery.form.js"></script>
        <script src="script/_fileUpload.js"></script>
    </body>
    </html>

    2.2 _fileUpload.js

    /**
     *_fileUpload.js 
     *
     * 
     */
    window.onload = function() {
        
        
        $("#mysubmit").bind("click", function(){
            $("#myform").ajaxSubmit({
                url: "myUpload.do",
                type: "post",
                success: function(data){
                    console.log(11111111);
                    console.log(data);
                },
                error: function(responseError){
                    console.log(22222222222);
                    console.log(responseError);
                }
                
            });
        });
    }

    2.3 MyUploadAction.java(继承自Action)

    package com.rocky.console.action;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;
    
    import com.rocky.console.form.MyUploadForm;
    import com.rocky.console.service.ResponseUtil;
    
    
    public class MyUploadAction extends Action {
    
        
        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                HttpServletResponse response) throws Exception{
            
            MyUploadForm myUploadForm = (MyUploadForm) form;
            FormFile uploadFile = myUploadForm.getUploadFile();
            String filetitle = myUploadForm.getFiletitle();
            System.out.println("111111"+filetitle);
            
            int fileSize = uploadFile.getFileSize();
            InputStream inputStream = uploadFile.getInputStream();
            System.out.println("fileSize::::::::"+fileSize);
            String path = "x:";
            String filename = path + File.separator + uploadFile.getFileName();
            FileOutputStream fos = new FileOutputStream(filename);
            byte[] b = new byte[1024];
            int len = -1;
            while((len = inputStream.read(b))!=-1){
                fos.write(b, 0, len);
            }
            fos.close();
            String result = "success";
            ResponseUtil.write(response, result, null);
            return null;
            
        }
    }

    2.4 MyUploadForm.java( 继承自ActionForm)

    package com.rocky.console.form;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.struts.action.ActionErrors;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;
    
    public class MyUploadForm extends ActionForm {
    
        /**
         * 
         */
        private static final long serialVersionUID = 6650496540449458586L;
        
        private FormFile uploadFile = null;
        
        private String filetitle;
        
        public String getFiletitle() {
            return filetitle;
        }
    
        public void setFiletitle(String filetitle) {
            this.filetitle = filetitle;
        }
    
        public ActionErrors validate(ActionMapping mapping,
                HttpServletRequest request) {
            return null;
        }
        
        public void reset(ActionMapping mapping, HttpServletRequest request) {
        }
    
        public FormFile getUploadFile() {
            return uploadFile;
        }
    
        public void setUploadFile(FormFile uploadFile) {
            this.uploadFile = uploadFile;
        }
    
    }

    2.5 struts-config.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "struts-config_1_2.dtd">
    
    <struts-config>
        <data-sources />
        <form-beans>
            <form-bean name="myUploadForm" type="com.rocky.console.form.MyUploadForm" />
        </form-beans>
        <global-exceptions />
        <global-forwards />
        <action-mappings>
            <!-- rocky myupload -->
            <action path="/myUpload" attribute="myUploadForm" name="myUploadForm" type="com.rocky.console.action.MyUploadAction" />
        </action-mappings>
        <message-resources parameter="ApplicationResources" />
    </struts-config>

    2.6 说明

    2.6.1 jquery.form.js 网上可以下载 http://malsup.com/jquery/form/#download

            使用var formData = new FormData(), 然后formData.append("myfile", document.getElementById("myfile").files[0]);form.append...

            当form表单field较多时 写很多 append很麻烦, 显然 ajaxSubmit方便很多

    2.6.2 前端过来的数据 通过 ActionForm 直接封装到其子类(MyActionForm)对象中 , 用FormFile接收file文件 用String等接收其他类型数据

            当然都是根据HTML 标签的name属性一一对应 来注入的

    2.6.3 ActionForm是怎么和自定义实现的bean(MyUploadForm) 对上的?

           在struts-config.xml中form-bean设置自己的那个bean,通过<action path="/myUpload" attribute="myUploadForm" name="myUploadForm" 

           来完成这种映射

     ----------------201706011806更新------------------

    3. 乱码问题

    当form表单field值为中文 上面的代码会出现乱码

    解决方案

    3.1 js部分 加上 contentType: "application/x-www-form-urlencoded; charset=utf-8",

    /**
     *_fileUpload.js 
     *
     * 
     */
    window.onload = function() {
        loadUpTypes();
        var cataSel = document.getElementById("_mrcType");
        cataSel.onchange = function(event){
            var stlId = cataSel.value;
            loadUpProcess(stlId);
        };
        loadUpProcess(cataSel.value);
        loadMmoSecret();
        $("#mysubmit").bind("click", function(){
            $("#mysubmit").attr({"disabled":"disabled"});
            $("#myform").ajaxSubmit({
                url: "myUpload.do",
                type: "post",
                contentType: "application/x-www-form-urlencoded; charset=utf-8",
                success: function(data){
                    console.log(data);
                    alert(data);
                    clearForm();
                    $("#mysubmit").removeAttr("disabled");
                },
                error: function(responseError){
                    console.log(responseError);
                    alert(responseError);
                    clearForm();
                    $("#mysubmit").removeAttr("disabled");
                }
                
            });
        });
        
        
    }
    
    function loadTemplate(){
        var dictArray = new Array();
        var loader = dhtmlxAjax.getSync("template.do?action=loadTemplates");                
        if(loader.xmlDoc.responseXML!=null){
            var nodes = loader.xmlDoc.responseXML.selectNodes("/mam-response/result");
            for(var i=0;i<nodes.length;i++){
                var v = nodes[i].text;
                var vid = nodes[i].getAttribute("id");
                
                var dict = new Array();
                dict.push(vid);
                dict.push(v);
    
                dictArray.push(dict);
            }
        }
        return dictArray;
    
    }
    
    function loadUpTypes(){
        var dictArray = loadTemplate();
        var sel1 = document.getElementById("_mrcType");
        sel1.innerHTML = "";
    //    var optionElement = document.createElement("OPTION");
    //    optionElement.setAttribute("value", "-1");
    //    var textNode = document.createTextNode("---请选择---");
    //    optionElement.appendChild(textNode);
    //    sel1.appendChild(optionElement);
        for(var i=0; i<dictArray.length; i++){
            var optionElement = document.createElement("OPTION");
            optionElement.setAttribute("value", dictArray[i][0]);
            var textNode = document.createTextNode(dictArray[i][1]);
            optionElement.appendChild(textNode);
            sel1.appendChild(optionElement);
        }
    }
    
    function loadUpProcess(stlId){
        var dictArray = new Array();
        var url = "wf.do?action=loadProcessDict2&type=上载&stlId=" + stlId;
        url = encodeURI(encodeURI(url));
        var loader = dhtmlxAjax.getSync(url);                
        if(loader.xmlDoc.responseXML!=null){
            var nodes = loader.xmlDoc.responseXML.selectNodes("/mam-response/result");
            for(var i=0;i<nodes.length;i++){
                var v = nodes[i].text;
                var vid = nodes[i].getAttribute("id");
                
                var dict = new Array();
                dict.push(vid);
                dict.push(v);
    
                dictArray.push(dict);
            }
        }
        
        var sel2 = document.getElementById("_mrcProcess");
        sel2.innerHTML = "";
    //    var optionElement = document.createElement("OPTION");
    //    optionElement.setAttribute("value", "-1");
    //    var textNode = document.createTextNode("---请选择---");
    //    optionElement.appendChild(textNode);
    //    sel2.appendChild(optionElement);
        for(var i=0;i<dictArray.length;i++){
            var optionElement = document.createElement("OPTION");
            optionElement.setAttribute("value", dictArray[i][0]);
            var textNode = document.createTextNode(dictArray[i][1]);
            optionElement.appendChild(textNode);
            
            sel2.appendChild(optionElement);
        }
    }
    
    function loadMmoSecret(){
        var sel3 = document.getElementById("_mmLevel");
        sel3.innerHTML = "";
    //    var optionElement = document.createElement("OPTION");
    //    optionElement.setAttribute("value", "-1");
    //    var textNode = document.createTextNode("---请选择---");
    //    optionElement.appendChild(textNode);
    //    sel3.appendChild(optionElement);
        var dictArray = [["0","非密"], ["1", "内部"],["2", "秘密"],["3", "机密"]];
        for(var i=0;i<dictArray.length;i++){
            var optionElement = document.createElement("OPTION");
            optionElement.setAttribute("value", dictArray[i][0]);
            var textNode = document.createTextNode(dictArray[i][1]);
            optionElement.appendChild(textNode);
            sel3.appendChild(optionElement);
        }
    }
    function clearForm(){
        $(':input','#myform') 
        .not(':button, :submit, :reset, :hidden') 
        .val('') 
        .removeAttr('checked') 
        .removeAttr('selected');
    }

    3.2 ActionForm的实现类 重写reset方法

        public void reset(ActionMapping mapping, HttpServletRequest request) {
            try {   
                request.setCharacterEncoding("utf-8");   
            } catch (Exception e) {    
            }  
        }

    3.3 Action实现类

    new String(myUploadForm.getUploadtime().getBytes("iso-8859-1"), "utf-8");

    new String(uploadFile.getFileName().getBytes("gbk"), "utf-8");

    package com.cdv.console.action;
    
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.PrintWriter;
    import java.io.UnsupportedEncodingException;
    import java.text.SimpleDateFormat;
    import java.util.Calendar;
    import java.util.Date;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.upload.FormFile;
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    
    import com.cdv.console.domain.SDevice;
    import com.cdv.console.domain.UOperationlog;
    import com.cdv.console.domain.Uploadinfo;
    import com.cdv.console.domain.mmo.Mmo;
    import com.cdv.console.domain.mmo.MmoFiles;
    import com.cdv.console.domain.mmo.MmoPackage;
    import com.cdv.console.form.MyUploadForm;
    import com.cdv.console.service.DeviceManager;
    import com.cdv.console.service.OperLogManager;
    import com.cdv.console.service.PandoraMAMLogger;
    import com.cdv.console.service.ResponseUtil;
    import com.cdv.console.service.UploadinfoManager;
    import com.cdv.console.service.mmo.FileObject;
    import com.cdv.console.service.mmo.MetaDataManager;
    import com.cdv.console.service.mmo.ObjectManager;
    import com.cdv.console.service.mmo.PackageManager;
    import com.cdv.console.service.wf.ProcessEngine;
    import com.cdv.util.GUIDUtil;
    import com.cdv.util.XMLUtil;
    
    
    public class MyUploadAction extends Action {
    
        
        public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
                HttpServletResponse response) throws Exception{
            
            MyUploadForm myUploadForm = (MyUploadForm) form;
            FormFile uploadFile = myUploadForm.getUploadFile();
            String mmoName = new String(myUploadForm.getMmoName().getBytes("iso-8859-1"), "utf-8");
            Uploadinfo uploadinfo = setUploadinfoValue(myUploadForm);
            int cataTemplateId = myUploadForm.getCataTemplateId();
            int processId = myUploadForm.getProcessId();
            int secretLevel = myUploadForm.getSecretLevel();
            long fileSize = uploadFile.getFileSize();
            String fileName = new String(uploadFile.getFileName().getBytes("gbk"), "utf-8");
            String usercode = (String) request.getSession().getAttribute("usercode");
            String extname = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            ObjectManager objectManager = new ObjectManager();
            long mmoId = objectManager.register(mmoName, cataTemplateId, secretLevel, usercode, "", "", "", "");
            Mmo mmo = objectManager.load(mmoId);
            String objectId = mmo.getMmguid();
            mmo.setOnlineFlag(1);
            objectManager.update(mmo);
            uploadinfo.setMmoId(mmoId);
            
            UploadinfoManager uploadinfoManager = new UploadinfoManager();
            Long addUploadinfo = uploadinfoManager.addUploadinfo(uploadinfo);
            
            DeviceManager deviceManager = new DeviceManager();
            List<SDevice> devices = deviceManager.findDevices("在线存储");
            int devId = devices.get(0).getId();
            
            PackageManager packageManager = new PackageManager();
            long packageId = packageManager.addPackage(mmoId, "", "", "原始素材", devId, false);
            
            String name = "/" +"mmfiles_" + Calendar.getInstance().get(Calendar.YEAR) + "/" + mmoId + "/" + packageId + "/" + fileName;
            MmoFiles mmoFiles = new MmoFiles();
            mmoFiles.setFileName(name);
            mmoFiles.setFileSize(fileSize);
            mmoFiles.setFileType(extname);
            mmoFiles.setFlag(0);
            mmoFiles.setGuid(GUIDUtil.get());
            mmoFiles.setMmoId(mmoId);
            mmoFiles.setPackage(new MmoPackage(packageId));
            FileObject fileObject = new FileObject();
            long fileId = fileObject.addFile(mmoFiles);
            
            InputStream inputStream = uploadFile.getInputStream();
            String rootDir = "o:";
            String path = rootDir + name.substring(0, name.lastIndexOf("/") + 1);
            File filePath = new File(path);
            if(!filePath.exists()){
                filePath.mkdirs();
            }
            String fullpathFilename = rootDir + name;
            FileOutputStream fos = new FileOutputStream(fullpathFilename);
            byte[] b = new byte[1024];
            int len = -1;
            while((len = inputStream.read(b))!=-1){
                fos.write(b, 0, len);
            }
            fos.close();
            
            ProcessEngine processEngine = new ProcessEngine();
            long instId = processEngine.createInstance(processId, mmoId, mmoName, usercode, null);
            processEngine.submit(instId);
            
            //mmometa
            Document document = DocumentHelper.createDocument();
            Element root = document.addElement("ObjectMetaData");
            Element object = root.addElement("Object");
            object.addAttribute("objectID", objectId);
            object.addAttribute("objectName", "");
            object.addAttribute("parentID", "");
            object.addAttribute("layerName", "节目层");
            object.addAttribute("fileId", fileId+"");
            object.addAttribute("stlId", cataTemplateId+"");
            object.addAttribute("trimin", 0+"");
            object.addAttribute("trimout", 0+"");
            object.addAttribute("mmLevel", secretLevel+"");
            Element  metaData = object.addElement("MetaData ");
            metaData.addAttribute("count", 0+"");
            metaData.addElement("GroupItems");
            Element plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "上传时间");
            plainItem.addAttribute("_id", "/Program/Description/Uploadtime");
            plainItem.addCDATA(uploadinfo.getUploadtime());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "单位");
            plainItem.addAttribute("_id", "/Program/Description/UploadCompany");
            plainItem.addCDATA(uploadinfo.getUploadCompany());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "上传人");
            plainItem.addAttribute("_id", "/Program/Description/Uploader");
            plainItem.addCDATA(uploadinfo.getUploader());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "联系电话");
            plainItem.addAttribute("_id", "/Program/Description/Telephone");
            plainItem.addCDATA(uploadinfo.getTelephone());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "标题");
            plainItem.addAttribute("_id", "/Program/Description/EventTitle");
            plainItem.addCDATA(uploadinfo.getEventTitle());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "时间");
            plainItem.addAttribute("_id", "/Program/Description/EventTime");
            plainItem.addCDATA(uploadinfo.getEventTime());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "地点");
            plainItem.addAttribute("_id", "/Program/Description/EventPlace");
            plainItem.addCDATA(uploadinfo.getEventPlace());
    
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "人物及事件");
            plainItem.addAttribute("_id", "/Program/Description/ManAndEvent");
            plainItem.addCDATA(uploadinfo.getManAndEvent());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "被采访人及发言人");
            plainItem.addAttribute("_id", "/Program/Description/Interviewee");
            plainItem.addCDATA(uploadinfo.getInterviewee());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "职务名称");
            plainItem.addAttribute("_id", "/Program/Description/PositionTitle");
            plainItem.addCDATA(uploadinfo.getPositionTitle());
    
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "资料来源(所属版权)");
            plainItem.addAttribute("_id", "/Program/Description/DataSource");
            plainItem.addCDATA(uploadinfo.getDataSource());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "关键词");
            plainItem.addAttribute("_id", "/Program/Description/Keyword");
            plainItem.addCDATA(uploadinfo.getKeyword());
            
            plainItem = metaData.addElement("PlainItem");
            plainItem.addAttribute("name", "内容描述(新闻稿)");
            plainItem.addAttribute("_id", "/Program/Description/DataDescription");
            plainItem.addCDATA(uploadinfo.getDataDescription());
            
            String data = XMLUtil.toString(document);
            MetaDataManager metaDataManager = new MetaDataManager();
            metaDataManager.setMeta(instId, mmoId, data);
            
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            UOperationlog log = new UOperationlog();
            log.setAuditClass(PandoraMAMLogger.AUDIT_CLASS__COMMON);
            log.setAuditsource("网页上传");
            log.setOperClass(PandoraMAMLogger.OPER_CLASS__IMPORT);
            log.setOperDesc(sdf.format(new Date()) + "用户 " + usercode + " 上传文件" + mmoName );
            log.setOperresult(PandoraMAMLogger.OPER_RESULT__SUCC);
            log.setOperTime(new Date());
            log.setIpadd(request.getRemoteAddr());
            log.setUserCode(usercode);
            log.setTruename("");
            new OperLogManager().createOperLog(log);
            
            String result = "success";
            PrintWriter out = response.getWriter();
            out.write(result);
            out.close();
            return null;
            
        }
        
        private Uploadinfo setUploadinfoValue(MyUploadForm myUploadForm) throws UnsupportedEncodingException{
            String uploadtime = new String(myUploadForm.getUploadtime().getBytes("iso-8859-1"), "utf-8");
            String uploadCompany = new String(myUploadForm.getUploadCompany().getBytes("iso-8859-1"), "utf-8");
            String uploader = new String(myUploadForm.getUploader().getBytes("iso-8859-1"), "utf-8");
            String telephone = new String(myUploadForm.getTelephone().getBytes("iso-8859-1"), "utf-8");
            String eventTitle = new String(myUploadForm.getEventTitle().getBytes("iso-8859-1"), "utf-8");
            String eventTime = new String(myUploadForm.getEventTime().getBytes("iso-8859-1"), "utf-8");
            String eventPlace = new String(myUploadForm.getEventPlace().getBytes("iso-8859-1"), "utf-8");
            String manAndEvent = new String(myUploadForm.getManAndEvent().getBytes("iso-8859-1"), "utf-8");
            String interviewee = new String(myUploadForm.getInterviewee().getBytes("iso-8859-1"), "utf-8");
            String positionTitle = new String(myUploadForm.getPositionTitle().getBytes("iso-8859-1"), "utf-8");
            String dataSource = new String(myUploadForm.getDataSource().getBytes("iso-8859-1"), "utf-8");
            String keyword = new String(myUploadForm.getKeyword().getBytes("iso-8859-1"), "utf-8");
            String dataDescription = new String(myUploadForm.getDataDescription().getBytes("iso-8859-1"), "utf-8");
            Uploadinfo uploadinfo = new Uploadinfo();
            uploadinfo.setUploadtime(uploadtime);
            uploadinfo.setUploadCompany(uploadCompany);
            uploadinfo.setUploader(uploader);
            uploadinfo.setTelephone(telephone);
            uploadinfo.setEventTitle(eventTitle);
            uploadinfo.setEventTime(eventTime);
            uploadinfo.setEventPlace(eventPlace);
            uploadinfo.setManAndEvent(manAndEvent);
            uploadinfo.setInterviewee(interviewee);
            uploadinfo.setPositionTitle(positionTitle);
            uploadinfo.setDataSource(dataSource);
            uploadinfo.setKeyword(keyword);
            uploadinfo.setDataDescription(dataDescription);
            
            return uploadinfo;
        }
    }
    View Code

     3.4 另外在网上看到源码解决方案 记录一下

    在包org.apache.struts.upload下,有一个类CommonsMultipartRequestHandler,它主要负责文件上传处理,
    它使用的是DiskFileUpload来上传文件, DiskFileUpload upload = new DiskFileUpload();它的默认编码为ISO-8859-1,

    因此对中文处理有乱码,可以在此修改它的编码:upload.setHeaderEncoding("utf8");

     

  • 相关阅读:
    Foxit 出mac 版本啦
    mac 上的latex (有很多链接,侵权请通知,一定删除)
    集合转数组
    select2搜索框查询加遍历
    下拉框回显
    柱状堆积图Echarts
    echarts X轴数据显示不全问题
    Map静态键值对
    如何配置pl/sql (本地客户端)连接远程oracle服务器
    自定义验证jquery.validate
  • 原文地址:https://www.cnblogs.com/rocky-fang/p/6900603.html
Copyright © 2020-2023  润新知