是这样的,Struts2 文件上传时,为防止文件同名的情况,我把文件名修改过了,并把原来的文件名保存在数据库,
在下载文件时,我想把文件以原来文件的文件名返回给客户端,应该如何做?下载的时候我是通过数据库的url获取文件的

解决方案 »

  1.   

    struts2的下载你写个下载的方法返回要下载的文件流即可(详细参考struts2的开发手册文件下载)。public DownloadAction extends ActionSupport{
      private InputStream is;
      private String fileName;
      public InputStream download(){
        is=new FileInputStream(你要下载的文件);
        return is;
      }
      public String getFileName() throws Exception{//关键在这里,在返回名称的地方要注意编码
         fileName=new String(fileName.getBytes(),"Iso-8859-1");
         return fileName;
      }
      setter,getter
    }struts.xml那边只要配置好下载的action<action name="download" class="DownloadAction">
      <result type="stream" name="success">
        <param name="inputName">download</param>
        <param name="contentDisposition">attachment;filename="${fileName}"</param>
      </result>
    </action>
      

  2.   


    这时候下载的文件的文件名还是上传以后重命名的文件吧?
    这个fileName是从action里面取到的,你可以在action里面的download方法里面就给这个fileName赋值,你想给他原名就原名给新名就新名。
      

  3.   

    文件名直接URLEncoder.encode(filename,"UTF-8")
      

  4.   

    Struts2 文件上传时,为防止文件同名的情况,我把文件名修改过了,并把原来的文件名在数据库保存起来,
    在下载文件时,我想把文件以原来文件的文件名返回给客户端,应该如何做?现在我是根据数据库的保存的url找不到文件,因为我上传时候把文件重命名了。
    public void loadFile() throws Exception {
    HttpServletResponse response = ServletActionContext.getResponse();
    response.setHeader("Pragma", "No-cache");
    response.setHeader("Cache-Control", "no-cache");
    OutputStream os = null;
    response.setContentType(ContentTypeUtil.getTypeByFileName(load.getFileUrl()));
    response.setHeader("content-disposition", "attachment;filename=" +load.getFileUrl());
    File file = new File(PropertyMgr.getProperty("uploadFilePath"), load.getFileUrl());
    InputStream in = null;
    try {
    os = response.getOutputStream();// 取得输出流  
    in = new BufferedInputStream(new FileInputStream(file), 16384);
    byte[] buffer = new byte[16384];
    int length;
    while ((length = in.read(buffer)) != 0)
    os.write(buffer,0,length);
    }catch( Exception e)
    {
    System.err.println(e.getMessage());
    }
    finally {
    if (in != null) {
    in.close();
    }
    if (os != null)
    os.flush();
    os.close();
    }
    }