服务端提供servlet供手机端下载(解决Android系统不能下载问题)

还是直接上代码了,看的更清楚。

package cn.ffcs.smartcity.exterior.web;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.regex.Pattern;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.ffcs.sm.dao.SMDao;
import cn.ffcs.smartcity.Constants;
import cn.ffcs.smartcity.cbusiness.om.SoftShareDownload;
import cn.ffcs.smartcity.cbusiness.services.ISoftShareService;
import cn.ffcs.smartcity.util.PropertiesUtil;


/**
 * 软件分享下载接口
 * @author linwei
 *
 */
public class SSDownload extends HttpServlet {
	
	private final static Logger log = Logger.getLogger(SSDownload.class);
	public final static String SOFTSHARE_DOWNLOAD_ADDR = PropertiesUtil.getProp().getProperty("softShareDownloadAddr");
	public final static String SOFTSHARE_DOWNLOAD_NAME = PropertiesUtil.getProp().getProperty("softShareDownloadName");
	private ISoftShareService softShareService;
	private SMDao smDao;
	
	/**
	 * Constructor of the object.
	 */
	public SSDownload() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		log.info("这边开始进入SoftShareDownloadServlet的GET方法。");
		String id = request.getParameter("id");
		if(id != null && !"".equals(id)) {
			//判断id必须是为数字才可以的
			boolean flag = this.isNumber(id);
			log.info("flag is " + flag);
			if(flag) {
				try {
//				String decryptStr = SimpleCryptoUtil.decrypt(Constants.ENCRYPT_CODE, invitecode);
//				if(decryptStr != null && !"".equals(decryptStr)) {
//					String[] temp = decryptStr.split(",");
//					softShareDownload.setInvitor(temp[0]);
//					if(temp.length > 1) {
//						softShareDownload.setBeinvitor(temp[1]);
//					}
//				}
					//在下载前进行数据库的插入操作
					SoftShareDownload softShareDownload = new SoftShareDownload();
					softShareDownload.setSsdId(this.smDao.getTableNextID(Constants.SMART_SSDOWNLOAD_SEQ));
					softShareDownload.setDownloadTime(new Date());
					softShareDownload.setSdpId(Integer.parseInt(id));
					softShareDownload.setFlag(Constants.SYS_NOFLAG);  //设置标识位为0,表示未下载
					softShareService.addDownloadRecord(softShareDownload);
					//进行下载操作
					doDownload(request, response);
					//进行更新操作
					softShareDownload.setFlag(Constants.SYS_YESFLAG); //设置标志位为1,表示成功下载
					softShareService.updateDownloadRecord(softShareDownload);
					
				} catch (Exception e) {
					log.error("parse and download file error,e is " + e.getMessage());
					throw new ServletException("parse and download file error,e is " + e.getMessage());
				}
			} else {
				log.error("解析到的ID有数字以外的字符。");
				//解析到的ID有数字以外的字符,也可以进行下载操作,但是不进入统计范畴
				doDownload(request, response);
			}
		} else {
			log.error("获取到的id为空。");
			//获取到的id为空,也可以进行下载操作,但是不进入统计范畴
			doDownload(request, response);
		}
		
	}

	private static boolean isNumber(String str) {
		
		Pattern pattern = Pattern.compile("[0-9]*");
		return pattern.matcher(str).matches();
	}
	
	
	private void doDownload(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		//获取对应文件的文件流
		File file = new File(SOFTSHARE_DOWNLOAD_ADDR+SOFTSHARE_DOWNLOAD_NAME);
		long fileLength = file.length();
		InputStream in = new FileInputStream(file);
		if(in != null) {
//			response.setContentType("application/x-download; charset=gb2312");
			//以下的类型必须要设置,要不不能在android机上正常下载的
			response.setContentType("application/vnd.android.package-archive; charset=gb2312");
			//设置文件的长度,以便能够正确的显示进度条
			response.setContentLength((int)fileLength);
			//添加文件名字的时候,需要添加对应的后缀
			response.addHeader("Content-Disposition","attachment;filename=" + new String(SOFTSHARE_DOWNLOAD_NAME.getBytes("gb2312"),"iso-8859-1")); 
			BufferedInputStream bufferInput = new BufferedInputStream(in);
			ServletOutputStream out = null;
			try {
				byte[] buffer = new byte[1024];
				out = response.getOutputStream();
				int len;
				while ((len = bufferInput.read(buffer)) > 0) {
					out.write(buffer, 0, len);
				}
				out.flush();
				response.setStatus(response.SC_OK);
				response.flushBuffer();
			} catch (IOException e) {
				throw e;
			} finally {
				if (out != null) {
					out.close();
				}
				if (bufferInput != null) {
					bufferInput.close();
				}
				if (in != null) {
					in.close();
				}
			}
		} else {
			throw new IOException("获取的流为空,请确定服务器对应的路径下是否有文件提供下载。");
		}
	}
	
	
	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		log.info("这边开始进入SoftShareDownloadServlet的POST方法,下面跳转至GET方法");
		doGet(request,response);
	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init(ServletConfig sc) throws ServletException {

		  super.init(sc); 
		  ApplicationContext appctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		  softShareService = (ISoftShareService)appctx.getBean("softShareService");
		  smDao = (SMDao)appctx.getBean("cn.ffcs.sm.dao.SMDaoImpl");
	}

	public ISoftShareService getSoftShareService() {
		return softShareService;
	}

	public void setSoftShareService(ISoftShareService softShareService) {
		this.softShareService = softShareService;
	}

	public SMDao getSmDao() {
		return smDao;
	}

	public void setSmDao(SMDao smDao) {
		this.smDao = smDao;
	}
	
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值