文件下载,可解决下载时各种异常及乱码,空格变+号

本来想写一个关于解决struts做视频上传下载时,各种问题异常的解决方案,但是上传要写的太多了,这里只写了个下载的例子及说明(以后有时间了再写上传视频的)。
先罗列一下上传及下载的常见问题吧:
上传:
一.上传
1。如何统计上传文件多大及已经上传多少(统计客户端向临时文件写的大小而不是文件服务器)?
2。如果上传文件大于struts2最大要求,如何给用户一个快速国际化的提示信息而不是等半天才提示
3。当用户点击取消按钮时,如何停止上传动作(用户点击取消的一瞬间,服务器端有可能正向文件服务器写入上传的文件,也有可能文件上传已经完成,正调用外部应用程序进行视频格式的转换或获取视频的截图【关键是这第二个可能,就是点击取消按钮的同时将外部程序这个子进程也杀掉】)
二.下载
1。用户取消问题
2。乱码,特殊符号问题及空格变加号

package com.common.util;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Properties;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.xwork.StringUtils;

public class DownloadFileUtils {

    //文件存放的目录
    public static String saveFileURL;

    /**
     * 根据上传文件获取其真实读取路径
     *
     * @param response
     * @param downloadRealName 服务器端文件的实际名字
     * @param fileSource       服务器端存放文件的目录
     * @param fileSrcName      存放文件的文件夹
     * @param fileName         下载后文件的名字
     * @return
     * @throws IOException
     */
    public static String downloadFile(HttpServletRequest request, HttpServletResponse response,
                                      String downloadRealName, String fileSrcName, String fileName) {

        InputStream fis = null;
        OutputStream toClient = null;
        try {
            String path = saveFileURL
                    + "\\" + fileSrcName
                    + "\\" + downloadRealName + fileName.substring(fileName.lastIndexOf("."), fileName.length());
            System.out.println("downloadPath----->" + path);
            File file = new File(path);
            if (!file.exists()) {
                return null;
            }
            fis = new BufferedInputStream(new FileInputStream(path));
            byte[] buffer = new byte[fis.available()];
            //byte[] buffer = new byte[1024];
            fis.read(buffer);
            fis.close();

            response.reset();
            System.out.println("downloadName---->" + fileName);
            fileName = encodeFileName(request, fileName);
            //解决下载时,空格变加号
            fileName = StringUtils.replace(fileName, "+", "%20");
            response
                    .addHeader("Content-Disposition", "attachment;filename="
                            + fileName);
            response.addHeader("Content-Length", "" + file.length()); // 设置返回的文件类型
            toClient = new BufferedOutputStream(response
                    .getOutputStream()); // 得到向客户端输出二进制数据的对象
            toClient.write(buffer); // 输出数据
            toClient.flush();
            toClient.close();
            return fileName;
        } catch (IOException e) {
            System.out.println("----------下载文件时,输出流发生异常--------------");
            try {
                if (null != fis) {
                    fis.close();
                }
                if (null != toClient) {
                    toClient.close();
                }

            } catch (IOException e1) {
                e1.printStackTrace();
            }

            return fileName;
        } catch (Exception e) {
            System.out.println("----------下载文件时发生异常--------------");
            return null;
        }
    }


    public static String encodeFileName(HttpServletRequest request,
                                        String fileName) throws UnsupportedEncodingException {
        String agent = request.getHeader("USER-AGENT");
        if (null != agent && -1 != agent.indexOf("MSIE")) {
            System.out.println("------IE浏览器下载");
            return URLEncoder.encode(fileName, "UTF8");
        } /*else if (null != agent && -1 != agent.indexOf("Mozilla")) {
			System.out.println("------火狐浏览器下载");
			return "=?UTF-8?B?"
					+ (new String(Base64.encodeBase64(fileName
							.getBytes("UTF-8")))) + "?=";
		}*/ else {
            System.out.println("------其它浏览器下载");
            //return fileName;
            return new String(fileName.getBytes(), "iso-8859-1");
        }

    }

    /**
     * 读取file.properties配置文件中的属性
     *
     */
    static {
        try {
            Properties props = new Properties();
            //得到当前类的类加载器,以流的方式读取配置文件   
            props.load(DownloadFileUtils.class.getClassLoader().getResourceAsStream("file.properties"));
            saveFileURL = props.getProperty("saveFileURL");
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

以上代码,基本可以解决下载时各种问题,但后台还有可能会报
一个异常,叫什么response.sendError(.....),类似这样一个错误,这是因为用户点击下载或取消时,页面发生了跳转,例如以我自己的例子说明:
我这里有个重定向的过滤器
filterChain.doFilter(servletRequest, servletResponse);
只要将上面做一下异常处理即可:
try {
filterChain.doFilter(servletRequest, servletResponse);
} catch (Exception e) {
System.out.println("----------页面跳转时,发生流异常--------------");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值