downloadfileservlet.java

来自「工厂版本管理系统,STRUTS2框架,用于管理商品的版本,便于有效的控制版本」· Java 代码 · 共 74 行

JAVA
74
字号
package com.bluesky.web.servlet;

import java.io.OutputStream;

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

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

import com.bluesky.common.domain.IReposity;
import com.utstar.fcs.domain.workinstruction.field.FileField;

public class DownloadFileServlet extends HttpServlet {
	private Logger log;

	public void init() {
		log = Logger.getLogger(this.getClass());

	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response) {

		XmlWebApplicationContext webContext = (XmlWebApplicationContext) getServletContext()
				.getAttribute(
						"org.springframework.web.struts.ContextLoaderPlugIn.CONTEXT.");

		WebApplicationContext wac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(getServletContext());

		IReposity reposity = (IReposity) wac.getBean("reposity");

		String uri = request.getRequestURI();
		String imageId = uri.substring(uri.lastIndexOf('/') + 1);
		if(imageId.trim().length()==0)
			return;
		
		long longfileId = Long.parseLong(imageId);

		FileField fileFieldEntity = null;

		byte[] imageData = null;

		if (imageId != null && imageId.trim().length() != 0) {
			String imageType = request.getParameter("type");
			if (imageType == null)
				imageType = "";
			if (imageType.equals("")) {
				fileFieldEntity = (FileField) reposity.get(FileField.class, longfileId);

				imageData = fileFieldEntity.getData();
			}
		}
		try {
			response.setHeader("Content-disposition","attachment;filename="+fileFieldEntity.getFileName());
			response.setContentType(fileFieldEntity.getContentType());

			OutputStream out = response.getOutputStream();
			out.write(imageData);
			out.flush();
			out.close();
		} catch (Exception e) {

		}
	} // end doPost()
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?