关于JSP中的文件上传
最近因为项目需要,做了一个XLS文件上传.但不知道如何下手.就拿来别人的代码看了一下.如下:
首先,在application-data.xml中添加:
<bean id="attachmentDao" name="code">/* * 创建日期: 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));}}}}
<bean id="attachmentHandle" ref="attachmentDao"/><property name="upload" ref="upload"/></bean>
<bean name="/Apply" parent="actionTemplate"> <property name="target"> <bean ref="attachmentHandle"/> </bean> </property></bean>
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;}
<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="删除" 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="删除" 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="增加附件" 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>
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;}
<!-- 附件添加删除部分的代码 --> <tr> <td 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>
<action path="/downLoadFileAction"></action>
<bean name="/downLoadFileAction" value="${fileURL}"/></bean>
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;}}