由于不同的servlet container在jsp的contentType和setHeader上处理不一样,所以我不推荐在jsp页面上使用download的代码。
我在ofbiz的架构上是这样处理的,upload file以后,将文件的content Type ,file path 等一些基本信息save起来,以下为Entity定义:
<entity entity-name="Attachment"
package-name="com.smics.pub"
title="Attachment Entity">
<field name="attachmentId" type="numeric"/>
<field name="attachmentType" type="id-ne"/>
<field name="path" type="long-varchar"/>
<field name="contentType" type="mid-varchar"/>
<field name="fileName" type="mid-varchar"/>
<field name="fileSize" type="numeric"/>
<field name="version" type="numeric"/>
<prim-key field="attachmentId"/>
</entity>
在request的时候,是在java里面处理,不返回jsp,一下是controller的定义:
<request-map uri="viewAttachment">
<security https="true" auth="true"/>
<event type="java" path="com.smics.util.attachment.DownloadEvents" invoke="download"/>
<response name="success" type="none"/>
</request-map>
在java代码里面利用entity的contentType和path来处理,以下是java code:
/*
* Created on 2003-8-18
*/
package com.smics.util.attachment;
/**
* @author Quake Wang
*/
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.ofbiz.core.util.*;
import org.ofbiz.core.entity.*;
public class DownloadEvents {
public static final String module = DownloadEvents.class.getName();
public static String download(HttpServletRequest request, HttpServletResponse response) throws Exception{
//get attachment info from database
GenericDelegator delegator = (GenericDelegator) request.getAttribute("delegator");
String attachmentId = request.getParameter("attachmentId");
//TODO: NPE check
GenericValue attachment = null;
try {
attachment = delegator.findByPrimaryKeyCache("Attachment", UtilMisc.toMap("attachmentId", attachmentId));
} catch (GenericEntityException gee) {
Debug.logError(gee, module);
return "error";
}
File f = new File(attachment.getString("path"));
FileInputStream in = new FileInputStream(f);
response.setContentType(attachment.getString("contentType"));
response.setHeader("Content-Disposition", "filename="+attachment.getString("fileName"));
response.setContentLength((int)f.length());
//fetch the file
int length = (int)f.length();
if(length != 0) {
byte[] buf = new byte[4096];
ServletOutputStream op = response.getOutputStream();
while ((in != null) && ((length = in.read(buf)) != -1)) {
op.write(buf,0, length);
}
in.close();
op.flush();
op.close();
}
//TODO: log hit
return "success";
}
}