关于JSP中的文件上传

最近因为项目需要,做了一个XLS文件上传.但不知道如何下手.就拿来别人的代码看了一下.如下:
首先,在application-data.xml中添加:
<bean id="attachmentDao" class="com.ibm.process.persistence.dao.ProcessAttachmentDAO">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>

这里用到了一个设计模式――工厂模式,用户程序从工厂类SessionFactory中取得Session的实例,可以用来刷新数据库.
SessionFactory在Hibernate中实际起到了一个缓冲区的作用,它缓冲了Hibernate自动生成的SQL语句和一些其它的映射数据,还缓冲了一些将来有可能重复利用的数据。

在com.ibm.process.persistence.dao.ProcessAttachmentDAO"中
/*
* 创建日期: 2006-4-29
* Version: 1.0
*/
package com.ibm.process.persistence.dao;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.ibm.process.persistence.pojo.ProcessAttachment;

/**
*
* TJMCC EIP II Copyright:IBM BCS
*
* @author fengfei
*
*/
public class ProcessAttachmentDAO extends HibernateDaoSupport {

//查询
public ProcessAttachment query(Integer fileId) {
java.util.List list = this.getHibernateTemplate().find(
"from ProcessAttachment a where a.fileId=?", fileId);
if (list == null || list.size() == 0)
return null;
return (ProcessAttachment) list.get(0);
}

//增加保存
public void add(ProcessAttachment attachment) {
this.getHibernateTemplate().save(attachment);
}

public void delete(ProcessAttachment attachment) {
this.getHibernateTemplate().delete(attachment);
}

//修改
public void modify(ProcessAttachment attachment) {
this.getHibernateTemplate().update(attachment);
}

//查询多个
public List queryAttachmentList(Integer processId) {
List list = null;
if (processId != null && !"".equals(processId)) {
list = this.getHibernateTemplate()
.find("from ProcessAttachment pc where pc.processId=?",
processId);
}
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
ProcessAttachment temp = (ProcessAttachment) list.get(i);
temp.setTempFileName(temp.getFileName().substring(14,
temp.getFileName().length()));
}

}
return list;
}

public List ListProcessAttachment(Integer processId) {
List list = null;
if (processId != null && !processId.equals("")) {
list = this.getHibernateTemplate()
.find("from ProcessAttachment pc where pc.processId=?",
processId);
}
if (list != null && list.size() > 0) {
for (int i = 0; i < list.size(); i++) {
ProcessAttachment temp = (ProcessAttachment) list.get(i);
temp.setTempFileName(temp.getFileName().substring(14,
temp.getFileName().length()));

}
}
return list;
}

//删除
public void removeByFormId(Integer processId) {
List list = this.queryAttachmentList(processId);

if (list != null) {
for (int i = 0; i < list.size(); i++) {
delete((ProcessAttachment) list.get(i));
}
}

}

}



其次,在application-service.xml中添加:
<bean id="attachmentHandle" class="com.ibm.process.web.fileupload.ProcessAttachmentHandler">
<property name="dao" ref="attachmentDao"/>
<property name="upload" ref="upload"/>
</bean>


再次,把ProcessAttachmentHandler注入到Spring中让Action使用.
<bean name="/Apply" parent="actionTemplate">
<property name="target">
<bean class="Action">
<property name="handle" ref="attachmentHandle"/>
</bean>
</property>
</bean>


在Action中添加如下代码:
import com.ibm.process.web.fileupload.ProcessAttachmentHandler;

private ProcessAttachmentHandler handle;

/**
* @return Returns the handle.
*/
public ProcessAttachmentHandler getHandle() {
return handle;
}

/**
* @param handle
* The handle to set.
*/
public void setHandle(ProcessAttachmentHandler handle) {
this.handle = handle;
}

try {
//查找附件
java.util.List attachments = handle.getDao().queryAttachmentList(Integer.valueOf(businessId));
request.setAttribute("attachments", attachments);
}
catch (Exception e) {
logger.error("get upload attachments error", e);
throw e;}


在JSP中添加代码如下图所示:
[img]http://duanfei.iteye.com/upload/picture/pic/22799/9be6fe61-c884-36be-a28d-5255ae299b40.bmp[/img]
<table width="100%" border="0">
<tr>
<td width="90%">
<table id="tblsales" width="100%" border="0" cellpadding="0" cellspacing="0">
<c:if test="${attachments!=null}">
<c:forEach items="${attachments}" var="attachment" varStatus="counter">
<tr><td></td></tr>
<tr>
<td id="span<c:out value='${counter.count-1}'/>" name="span<c:out value='${counter.count-1}'/>">
<table>
<tr>
<td width="88%">
<input type="file" name="uploadFile[<c:out value='${counter.count-1}'/>].file" value="" size="50"/><a href="<%= request.getContextPath()%>/downLoadFileAction.do?filename=<c:out value='${attachment.fileName}'/>"><c:out value="${attachment.tempFileName}"/></a>
<input type="hidden" name="uploadFile[<c:out value='${counter.count-1}'/>].fileId" value="${attachment.fileId}"/>
<input type="hidden" name="fileId" value="<c:out value='${attachment.fileId}'/>"/>
<input type="hidden" name="deleteFileId" value=""/>
</td>
<td width="2%"></td>
<td width="10%"><input type="button" name="DeleteFile"+"${counter.count-1}" value="删除" class="button_2" onClick="deleteAtt('<c:out value='${counter.count-1}'/>')"/></td>
</tr>
</table>
</td>
</tr>
</c:forEach>
</c:if>
<c:if test="${attachments==null}">
<tr>
<td id="span0" name="span0">
<table>
<tr>
<td width="88%">
<input type="file" name="uploadFile[0].file" value="" size="50"/>
<input type="hidden" name="uploadFile[0].fileId" value=""/>
<input type="hidden" name="fileId" value="">
<input type="hidden" name="deleteFileId" value=""/>
</td>
<td width="2%"></td>
<td width="10%"><input type="button" name="DeleteFile0" value="删除" class="button_2" onClick="deleteAtt(0)"/></td>
</tr>
</table>
</td>
</tr>
</c:if>
</table>
</td>
<td width="10%" valign="top" style="padding-top:2px">
<span style="padding-left:10px">
<input type="button" name="Submit4223" value="增加附件" class="button_4" onClick="addToTable()">
<input type="hidden" name="attsize"
value="<c:if test='${attachments==null}'>1</c:if><c:if test='${attachments!=null}'><c:if test='${attsize!=null}'><c:out value='${attsize}'/></c:if><c:if test='${attsize==null}'>0</c:if></c:if>"/>
</span>
</td>
</tr>
</table>


<!-- 添加附件与删除附件的方法 -->
<script language="javascript" type="">

function addToTable(){
var the_table = document.all("tblsales");
var attsizeObj = document.all("attsize");
trId = attsizeObj.value;

var the_row,the_cell;
the_row = -1;
var newrow=the_table.insertRow(the_row);
newrow.insertCell();
newrow.cells(0).id="span"+trId;
newrow.cells(0).name="span"+trId;
tmpHTML = "<table><tr><td width='88%'>";
tmpHTML = tmpHTML+"<input type='file' name='uploadFile["+trId+"].file' value='' size='50'>" + "<input type='hidden' name='uploadFile["+trId+"].fileId' value=''>" + "<input type='hidden' name='fileId' value=''>" + "<input type='hidden' name='deleteFileId' value=''>";
tmpHTML = tmpHTML+"</td>";
tmpHTML = tmpHTML+"<td width='2%'></td>";
tmpHTML = tmpHTML+"<td width='10%'><input type='button' name='DeleteFile"+trId+"' value='删除' class='button_2' onClick='deleteAtt("+trId+")'/></td>";
tmpHTML = tmpHTML+"</tr></table>";
newrow.cells(0).innerHTML=tmpHTML;
trId++;

attsizeObj.value=trId;
}

function deleteAtt(attid){
var att=document.getElementById("span"+attid);
att.style.display="none";
var arraydelete=document.all("deleteFileId");
if(arraydelete!=null)
{
if(attid==0)
{
if(arraydelete[0]==null)
{
if(arraydelete!=null)
{
arraydelete.value="y";
}
}
if(arraydelete[0]!=null)
{
arraydelete[attid].value="y";
}
}
else
{
arraydelete[attid].value="y";
}
}
}
</script>


在另一个Action中保存附件.

private ProcessAttachmentHandler handle;
/**
* @return Returns the handle.
*/
public ProcessAttachmentHandler getHandle() {
return handle;
}
/**
* @param handle The handle to set.
*/
public void setHandle(ProcessAttachmentHandler handle) {
this.handle = handle;
}

String templateName = "SPContractProcess";
int val = (int) apply.getId().longValue();
Integer processId = null;
if (val < 0) {
val = -val;
}
String[] fileId = applyForm.getFileId();
String[] deleteFileId = applyForm.getDeleteFileId();
processId = Integer.valueOf("" + val);
try {
ProcessAttachment processAttachment = new ProcessAttachment();
processAttachment.setFileUser(user.getUserName());
processAttachment.setTemplateName(templateName);
processAttachment.setProcessId(processId);
handle.modifyAttachment(applyForm, processAttachment, fileId,
deleteFileId);
} catch (Exception e) {
// logger.error("upload files error", e);

throw e;
}


在approval中只显示出附件的做法:
如图所示:
[img]http://duanfei.iteye.com/upload/picture/pic/22801/179e7e47-a5f2-3aab-85ae-bcaa303e725b.bmp[/img]
<!-- 附件添加删除部分的代码 -->
<tr>
<td class="table_color_1"></td>
<td height="25" class="lshowtd">附件:</td>
<td colspan="5" class="l_line">
<table width="100%" border="0">
<tr>
<td width="82%" valign="top">
<table width="100%" border="0" cellpadding="0" cellspacing="0" id="tblsales">
<c:if test="${attachments!=null}">
<c:forEach items="${attachments}" var="attachment" varStatus="counter">
<tr>
<td><a href="<%= request.getContextPath()%>/downLoadFileAction.do?filename=<c:out value='${attachment.fileName}'/>"><c:out value="${attachment.tempFileName}"/></a></td>
</tr>
</c:forEach>
</c:if>
<c:if test="${attachments==null}">
<tr>
<td> </td>
</tr>
</c:if>
</table>
</td>
</tr>
</table>
</td>
</tr>


在点击xls时,执行了downLoadFileAction.do的动作.分别在Struts与Spring中配置如下:
struts-application.xml
<action path="/downLoadFileAction">
</action>

application-servlet.xml
<bean name="/downLoadFileAction" class="com.ibm.process.struts.action.DownLoadFileAction">
<property name="fileURL" value="${fileURL}"/>
</bean>


在DownLoadFileAction中代码如下:
public class DownLoadFileAction extends BaseAction {
private String fileURL;

public String getFileURL() {
return fileURL;
}

public void setFileURL(String fileURL) {
this.fileURL = fileURL;
}

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
ActionForward temp = null;
String filename = request.getParameter("filename");
String filetemp = request.getParameter("filename");
if (filetemp != null && !"".equals(filetemp) && filetemp.length() >= 14) {
filetemp = filetemp.substring(14, filetemp.length());
}
// filetemp = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
// filename = new String(filename.getBytes("GBK"), "ISO-8859-1");
// filename = new String(filename.getBytes("GB2312"), "ISO-8859-1");

// filename = new String(filename.getBytes("ISO8859-1"), "UTF-8");
// filename = new String(filename.getBytes("ISO8859-1"), "GBK");
// filename = new String(filename.getBytes("ISO8859-1"), "GB2312");

// filename = URLEncoder.encode(filename, "ISO8859-1");
filetemp = URLEncoder.encode(filetemp, "UTF-8");
// filename = URLEncoder.encode(filename, "GB2312");

// filename = URLEncoder.encode(filename, "GBK");

// filename = new String(filename.getBytes("ISO8859-1"), "UTF-8");
// filename=URLEncoder.encode(filename,"GBK");
// filename=new String(filename.getBytes("GBK"), "ISO-8859-1");
response.setContentType("application/octet-stream");
// response.setContentType("application/octet-stream; charset=UTF-8");

response.setHeader("Content-disposition", "attachment; filename="
+ filetemp);
BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
// EIPLogger.debug("FileName:"+fileURL+filename);
// fileURL="/portal/";
File file = new File(fileURL + filename);
bis = new BufferedInputStream(new FileInputStream(file));
bos = new BufferedOutputStream(response.getOutputStream());
bos.flush();
byte[] buff = new byte[12048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (final IOException e) {
System.out.println("File Download IOException.\n" + e);
} catch (Exception e) {
e.printStackTrace();

} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
return null;

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值