我下载时是直接读到服务器端文件。但由于服务器端文件利用uuid命名,下载的时候显示给用户的就是这个uuid,很不方便,有没有方法可以不改变其他地方,就可以使用户下载时看到的文件名显示成其他形式呢?比如我已经存在数据库里的该文件上传时的文件名

解决方案 »

  1.   

    如果嫌名字难看,可以这样:
      /xxoo/download/文件名称.扩展名?uuid=123122365264328764
    然后Servlet直接映射到 download 上。处理时可以彻底忽略“文件名称.扩展名”,直接按照uuid来查找;也可以找到后检查下该UUID跟文件名是否匹配。
    如果不喜欢带参数,也可以:
      /xxoo/download/1836238764283445245/文件名称.扩展名
    反正机制都差不多。
      

  2.   

    在servlet代码中设置:HttpServletResponse response
    response.setContentType("application/vnd.ms-excel;charset=UTF-8");            
    response.setHeader("Content-Disposition", "attachment;filename=report.xls");这里文件名就是report.xls
      

  3.   

    在上传的时候就要把原文件名保存到数据库,
    在下载的时候仍然把这个文件名输出到客户端,
    /**
     * 下载文件
     * @param filePath 文件路径(物理路径)
     * @param fileName 源文件名称(中文也可以)
     */
    public void downLoadFile(String filePath, String fileName) {
    File file = new File(filePath);
    if (!file.exists() || file.isDirectory()) {
    return;
    }
    InputStream input =null;
    OutputStream output = null;
    try {
    input = new FileInputStream(file);
    output = getResponse().getOutputStream();
    getResponse().setHeader("Content-disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    byte[] buffer = new byte[1024];
    int i = 0;
    while ((i = input.read(buffer)) != -1) {
    output.write(buffer, 0, i);
    }
    } catch (Exception e) {} finally {
    try {
    if(null !=output) {
    output.flush();
    output.close();
    }
    if(null !=input) {
    input.close();
    }
    } catch (Exception e) {}
    }
    }