structs文件上傳與下載,解決文件亂碼的例子

easyUI的界面。注意下載時將中文的文件名經過兩次編碼傳遞到action,ie下不用先轉回,再經過轉碼纔到xml文件,直接就可以映射到xml文件。

jsp:

<body class="easyui-layout">
    <s:form id="form" enctype="multipart/form-data">
    <div data-options="region:'center',border:false" style="padding:5px;">
     <table id="tablegrid"></table>
     </div>
         <div data-options="region:'south',border:false" style="height:100px;padding:5px;">        
            <input type = "file" name="attachment" id="attachment" style="width:200px;" /><br />
            <input class="defBtn" type="button" value="上傳" onclick="uploadFile()" />&nbsp;&nbsp;
            <input class="defBtn" type="button" value="取消" onclick="cancal()" />
            </div>
    </s:form>              
</body>

  

js:   
var grid = null;
    var cols = [
        {title:'主鍵',field:'id',checkbox:true},
        {title:'文件名',field:'fileName',align:'center',formatter:downloadFormatter},
        {title:'大小(KB)',field:'size',align:'center'},
   
    ];    
        
    $(function() {
      grid = xGrid({
        id: 'tablegrid',
        title : '文件列表',
        url : base + '/in/files/filesList.action',
        idField : 'id',
        pagination : true,
        singleSelect:false,
        columns : [cols],
    });  
    });
               
    //上傳文件
    function uploadFile(){    
      var attachment = $('#attachment').val();
      var ext= attachment.substring(attachment.lastIndexOf(".")+1);
        if(!isNotNull(attachment)) {
            showMsg('請先選擇文件!');
            return;
        }if(fileFormat!=ext) {
            showMsg('上傳文件後綴名不正確!');
            return;
        }if (!isNotNull(tableName)) {
            showMsg('請先輸入表名!');
            return;
        }     
        $('#form').form('submit', {    
            url :  base + '/in/files/uploadFiles.action?files.size='+fileSize,
              success : function(result) {
                 var result = eval('(' + result + ')');
                if (result.success) {
                    parent.$.messager.alert('提示', result.msg);
                } else {                
                    parent.$.messager.alert('提示', result.msg);
                }
                searchThis();
                //避免上傳後立即點擊下載出現只能下載剛上傳的文件  
                window.location.reload();
            }      
        });
    }
    
    //下載文件
    function downloadFormatter(val,row,ind){
        var html = new Array();
        html.push('<a href="javascript:download(\''+row.id+'\',\''+row.fileName+'\')">');
        html.push(val);
        html.push('</a>');
        return html.join('');
    }
    
    function download(id,fileName){
        $.messager.confirm("提示","確定下載該文件",function(y){
            if (y) {            
                var url = base + '/in/files/getDownloadFiles.action?filesVO.id=' +id+'&attachmentFileName='+encodeURI(encodeURI(fileName));
                $('#form').attr('action', url);
                $('#form').submit();
                }
            });
    }
    
    
/* 多文件上傳
 *function addFile(){
        var file = document.createElement("input");
        file.type="file";
        file.name="attachment";
        file.id="attachment";
        document.getElementById("fileList").appendChild(file);
        document.getElementById("fileList").appendChild(document.createElement("br"));
    } */
    
    //刷新頁面
    function searchThis() {
        grid.datagrid('load', null);
        grid.datagrid('clearSelections');    
    }
    function cancal(){
        mainWindow.searchThis();
        mainDialog.window('close');
    }


action:


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import com.pk.core.action.GenericAction;
import com.pk.core.entity.Json;
import com.pk.util.DateConverter;
import com.pk.util.PropertiesUtil;
import com.platform.common.entity.Files;
import com.platform.common.service.FilesService;
import com.platform.common.vo.FilesVO;
import com.platform.util.PlatformConstant;
import com.privilege.user.entity.User;


@Controller
public class FilesAction extends GenericAction {

    @Autowired
    private FilesService filesService;
    private FilesVO filesVO = new FilesVO();
    private Files files = new Files();
    private InputStream inputStream;
    private String ids;
    private String aliasName;//文件別名
    private String fileName;//文件名(非UUID,解碼後)
    Json resultJson = new Json();    
    

    public String toFilesManage() {
        return "toFilesManage";
    }
    
    public void filesList(){
        List<FilesVO> filesList = new ArrayList<FilesVO>();
        filesList = filesService.filesList(filesVO);
        super.writeJson(filesList);
    }

    public void deleteFile(){
        if(StringUtils.isNotBlank(ids)) {        
            String[] idArray = ids.split(",");
            for(String id: idArray){
               files = filesService.getFile(id);          
               File file = new File(this.getSaveFilesPath()+"/"+files.getAlias());
               if(file.exists() && file.isFile()){
                    file.delete();
               }
               filesService.deleteFile(id);
            }
        }
    }
    
   //return the path of Files  
    public String getSaveFilesPath() {
        String formateDate = null;
        if(null!=files.getCreateTime()) {//downLoad and delete File
        Date createTime=files.getCreateTime();
        formateDate = DateConverter.dateToString(createTime, DateConverter.FORMAT_SEVEN);
        }else{//upLoad File
            formateDate = DateConverter.dateToString(new Date(), DateConverter.FORMAT_SEVEN);
        }
        String tableName = files.getTable();
        PropertiesUtil pu = new PropertiesUtil(PlatformConstant.PROPERTIES_PATH);    
        String saveFilesUrl = pu.getValue("fileUploadPath")+"/"+tableName+"/"+formateDate;
        return saveFilesUrl;
    }
    
     //upLoad File
    public void uploadFiles(){    
        //後綴名
       /*attachmentContentType=attachmentFileName.substring(attachmentFileName.lastIndexOf(".")+1);
       if(!attachmentContentType.equalsIgnoreCase(fileFormat)){    
            resultJson.setSuccess(false);
            resultJson.setMsg("上傳文件格式不正確");
            writeJson(resultJson);
            return;
         }*/
       //真實文件大小
       double size = attachment.length()/1024d;
       Double fileSize = files.getSize();
       if (null!=fileSize) {
           if(size>fileSize){    
               resultJson.setSuccess(false);
               resultJson.setMsg("上傳文件過大");
               writeJson(resultJson);
               return;
        }      
      }
       //查詢數據庫表並比較
       List<FilesVO> allTables = filesService.findAllTables();
       boolean flag = false;
           for(FilesVO tableNames : allTables) {
                if(files.getTable().equalsIgnoreCase(tableNames.getTableName())){
                     flag = true;
                     break;       
              }
           }
          
       if (!flag) {
           resultJson.setSuccess(false);
           resultJson.setMsg("不存在 "+filesVO.getTable()+"表");
           writeJson(resultJson);
        }else{
            // 保存的文件別名,使用UUID+後綴進行保存
            aliasName = UUID.randomUUID().toString()+ getExt(attachmentFileName);
            //獲取保存文件的路徑
            String target=getSaveFilesPath()+"\\"+aliasName;                
            File targetFile=new File(target);                
                 try {
                     //複製文件內容
                     FileUtils.copyFile(attachment, targetFile);          
                 } catch (IOException e) {
                   e.printStackTrace();
              }         
               this.saveFiles(); //保存文件
               resultJson.setSuccess(true);
               resultJson.setMsg("上傳成功!");
               writeJson(resultJson);
        }    
    }
     private String getExt(String attachmentFileName) {
          return attachmentFileName.substring(attachmentFileName.lastIndexOf("."));
    }

     //保存文件
    public void saveFiles(){  
        String formateDate =DateConverter.dateToString(new Date(), DateConverter.FORMAT_SEVEN);
        User loginUser = (User) super.getSession().getAttribute(PlatformConstant.USER);
        String url="/"+files.getTable()+"/"+formateDate+"/"+attachmentFileName;          
        files.setSize(attachment.length()/1024d);
        files.setCreator(loginUser.getUsername());
        files.setCreateTime(new Date());
        files.setUrl(url);
        files.setTable(files.getTable());
        files.setFileName(attachmentFileName);
        files.setAlias(aliasName);
        files.setRecordId(files.getRecordId());
        
        filesService.saveFiles(files);
        }    
    
    //downLoad Files
    public String getDownloadFiles() throws IOException {
        String id = filesVO.getId();
        if (StringUtils.isNotBlank(id)) {
            files = filesService.findFiles(id);        
        }    
        this.inputStream = new FileInputStream(getSaveFilesPath()+"/"+files.getAlias());
        return "downloadSuccess";
    }    
    public InputStream getInputStream() throws UnsupportedEncodingException {    
        String agent = ServletActionContext.getRequest().getHeader("USER-AGENT");//獲取用戶瀏覽器
        //防止下載文件名亂碼            
          if (null != agent) {
             if (-1 != agent.indexOf("Firefox") || -1 != agent.indexOf("Chrome")) {// Firefox + Chrome
                  fileName = URLDecoder.decode(attachmentFileName, "UTF-8");
                  fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
              }else{//IE              
                  ServletActionContext.getResponse().setHeader("Content-Disposition","attachment;fileName="+attachmentFileName);
            }
          }
        return inputStream;
    }
    
    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public FilesService getFilesService() {
        return filesService;
    }

    public void setFilesService(FilesService filesService) {
        this.filesService = filesService;
    }

    public FilesVO getFilesVO() {
        return filesVO;
    }

    public void setFilesVO(FilesVO filesVO) {
        this.filesVO = filesVO;
    }

    public String getIds() {
        return ids;
    }

    public void setIds(String ids) {
        this.ids = ids;
    }

    public File getAttachment() {
        return attachment;
    }

    public void setAttachment(File attachment) {
        this.attachment = attachment;
    }

    public Files getFiles() {
        return files;
    }

    public void setFiles(Files files) {
        this.files = files;
    }

    public String getAliasName() {
        return aliasName;
    }

    public void setAliasName(String aliasName) {
        this.aliasName = aliasName;
    }

    public String getFileName() throws Exception{
        return fileName;
    }
    public void setFileName(String fileName) throws Exception{
        this.fileName = fileName;
    }

}

xml:

    <action name="*" class="com.platform.common.action.FilesAction" method="{1}">
            <result name="toFilesManage">/platform/in/common/filesManage.jsp</result>        
           
            <!-- 下載文件  -->     
             <result name ="downloadSuccess" type="stream">
            <param name="inputName">inputStream</param>
            <param name="contentDisposition">attachment;fileName="${fileName}"</param>
         </result>  
         
       <!-- 上傳文件  -->
          <interceptor-ref name="fileUpload">
          <param name="maximumSize">20000000</param>        
            </interceptor-ref>
              <interceptor-ref name="defaultStack" />
        </action>

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章