文件上传

jsp页面


<tr>
       <td colspan="3" class=" xyz-field-collapse">
          <div>
               <div class="uploadPanel">
                     <a href="#" id="attachAddLink" class="underline-link attach-add">添加附件</a>
                     <div id="attachFile">
                          <input id="attachFileInfo" name="attachFileInfo" type="file"/>
                     </div>

                     <!-- 上传文件游览列表  -->
                     <ul id="attach_upload_list" style="max-height:150px; overflow-y:auto;"></ul>
              </div>
         </div>
     </td>
     <td style="text-align: right;">

         <!-- 上传按钮 -->
         <div id="attachContractDlgForm_btnUpload" />
    </td>
</tr>

js(基于Extjs的文件上传)


//获取文件名
var getFileName = function(str){
      var reg = /[^\/]*[\/]+/g;
      var str = str.replace(reg, '');
      return str;
};
//文件上传
var uploadFile = function(fileName){
    Ext.Ajax.service({
        url : SERVICE.UPLOAD_FILE_URL,
        jsonData : {},
        success : function(jsonSrc){
            var data = jsonSrc.getData();
                if(data.retCode == '-1') {
                    Ext.MessageBox.alert("提示", "添加附件失败,原因:" + data.msg);
                } else {
                    var attachDTO = data.dto;
                    addAttachMap(attachDTO);
                    appendAttachLink(attachDTO);
                }
                   fileField.reset();
            },
            failure : function(jsonSrc) {
                Ext.MessageBox.alert("提示", "添加附件失败,原因:" + jsonSrc.getMessage());
            },
            params :{
                fileName : fileName,
                attachType : attachTypeCombox.getValue()
            },
            form : "attachContractDlgForm",
            isUpload : true
        });
    };
//添加map
    var addAttachMap = function(attachDTO){
        var key = attachDTO.fileId;
        attachMap.add(key, attachDTO);
    };
    
     //添加附件列表节点
    var appendAttachLink = function (attachDTO) {
        var fileSize = attachDTO.fileSize;
        var tpl = new Ext.Template(
                '<li fileId="{fileId}">',
                '<span >' + attachDTO.fileName + ' (' + fileSize + ')' + '</span>',
                '<a href="#" class="del-link">删除 </a>',
                '</li>');
        tpl.append('attach_upload_list', attachDTO);
        Ext.select("#attach_upload_list li[fileId=" + attachDTO.fileId
             + "] > a.del-link").on("click", delAttachEvent);
        Ext.get("attach_upload_list").addClass(uploadBorderCls);
    };
struts2中的Action代码:
byte
[] fileByteData = null; InputStream in = null; ByteArrayOutputStream out = new ByteArrayOutputStream(); try { in = attachFileInfo.getInputStream(); byte[] buff = new byte[1024]; int len = 0; while((len = in.read(buff, 0 ,100)) != -1){ out.write(buff, 0, len); } fileByteData = out.toByteArray(); //获取内存缓冲中的数据 } catch (Exception e) { map.put("retCode", "-1"); map.put("msg", e.getMessage()); e.printStackTrace(); return map; }finally{ if(out != null){ try { out.close(); } catch (IOException e) { e.printStackTrace(); } } if(in != null){ try { in.close(); } catch (IOException e) { e.printStackTrace(); } } }
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        try {
//根据文名,获取文件的格式

             String fileName = dto.getFileName();
             int index = fileName.lastIndexOf(".");
             if(index > 0){
                String fileType = fileName.substring(index+1);
                dto.setFileFormat(fileType);
             }

            //设置文件的大小
            Double fileSizeKB = fileSize / 1024.0;
            DecimalFormat df = new DecimalFormat("########0.00");    //格式化数据
            String fileSizeStr = df.format(fileSizeKB);
            dto.setFileSize(fileSizeStr + "KB");          

              Date today = new Date();
              SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
              String todayStr = dateFormat.format(today);
              //设置当前日期为相对路径
              dto.setRelUrl(todayStr);

            DmStdTrInstrAttachDTO tempDTO = dmStdTrInstrAttachCtrl.addContractDmAttachMgr(sessionId, dto);

             //获取文件保存路径
             String path = this.getSysPath(sessionId);
             String fileFullPath = path + todayStr + "/" + tempDTO.getFileName();

            File file = new File(fileFullPath);
//文件不存在就创建文件
if(file!= null && !file.exists()){ new File(file.getParent()).mkdirs(); file.createNewFile(); } fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); //向文件写入数据 bos.write(fileByteData); bos.close(); fos.close(); return tempDTO; } catch (Exception e) { e.printStackTrace(); throw new ShineException(e.getMessage()); }finally{ if(fos != null) try { fos.close(); } catch (IOException e) { e.printStackTrace(); } if(bos != null) try { bos.close(); } catch (IOException e) { e.printStackTrace(); } }

 

原文地址:https://www.cnblogs.com/hongwz/p/5323097.html