Servlet 下载文件

项目中使用struts2 下载文件,使用手机浏览器有问题,老是报

java.lang.IllegalStateException: Cannot call sendError() after the response has been committed

没办法了,就使用servlet下载apk文件。

servlet类如下:

package com.shop.jn.web.servlet;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

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

import org.apache.commons.lang.StringUtils;

import com.common.util.SystemUtil;
import com.io.hw.file.util.FileUtils;

/**
 *  download apk
 */
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public DownloadServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		OutputStream out = response.getOutputStream();
		// must be linux path(not \\)
		String filepath = request.getParameter("filepa");
		if (StringUtils.isEmpty(filepath)) {
			filepath = "D:\\eclipse\\workspace\\apkmarket\\upload\\mpc.apk";
		}
		File file = new File(filepath);
		response.addHeader("Content-Disposition", "attachment;filename="
				+ SystemUtil.getFileSimpleName(filepath));
		response.setContentType("application/octet-stream");
		byte[] bytes = FileUtils.readBytes4file(file);
		System.out.println("size:" + bytes.length);
		response.addHeader("Content-Length", "" + bytes.length);
		out.write(bytes);
		return;
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

 使用servlet之后,手机浏览器仍然有问题,后来发现是因为路径分隔符的问题。

上述servlet需要一个请求要素,就是文件路径。

手机浏览器中,点击一个超链接就开始下载,超链接形如download.do?filepath=D:\eclipse\workspace\apkmarket\upload\mpc.apk

这时,就会下载失败,经过反复测试、尝试,发现路径分隔符有问题,改为:download.do?filepath=D:/eclipse/workspace/apkmarket/upload/mpc.apk 就好了。

说明:手机是安卓系统。

 

注意:

(1)安卓手机浏览器下载文件时,下载的超链接中文件路径应该使用linux的格式(xxx/xxx/xxx/);

(2)下载servlet中要指定ContentType 为"application/octet-stream"

 

你可能感兴趣的:(android,servlet,下载文件,download,手机浏览器)