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="上传" οnclick="uploadFile()" />&nbsp;&nbsp;
            <input class="defBtn" type="button" value="取消" οnclick="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>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值