读书人

jbos + struts1 + jsp 下传上载

发布时间: 2012-10-18 13:46:55 作者: rapoo

jbos + struts1 + jsp 上传下载

import java.io.File;

import java.io.FileOutputStream;

import java.io.OutputStream;

?

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

?

import org.apache.log4j.Logger;

import org.apache.struts.action.Action;

import org.apache.struts.action.ActionForm;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.upload.FormFile;

?

import com.hymake.wygl.shared.GetBusinessHome;

import com.hymake.wygl.shared.ShareModel;

import com.hymake.wygl.shared.business.XmxxBusiness;

import com.hymake.wygl.shared.business.XmxxBusinessHome;

?

/**

?* @author Jan 14, 2011 项目信息模块内容 上传 临时管理规约 附件(word) <br>

?*/

public class DoUploadItemAttachAction extends Action {

?? ? File fileContent;

static Logger logger = Logger.getLogger(ShareModel.class.getName());

public ActionForward execute(ActionMapping mapping, ActionForm form,

HttpServletRequest request, HttpServletResponse response)

throws Exception {

ItemAttachForm itemAttachForm = new ItemAttachForm();

itemAttachForm = (ItemAttachForm) form;

request.setAttribute("entId", itemAttachForm.getItem_id());

request.setAttribute("type", itemAttachForm.getType());

System.out.println("读取文件的URL: "+itemAttachForm.getFilePath());

System.out.println("服务器提交URL: "+request.getServletPath());

System.out.println("项目工程Name: "+request.getContextPath());

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

System.out.println("网络地址:"+basePath);

int MAX_FILE_SIZE =1024 * 1024 * 10;

XmxxBusinessHome xmxxBusinessHome;

XmxxBusiness xmxxBusiness;

OutputStream ?fos = null;

try {

FormFile formFile=itemAttachForm.getFileContent();

if(formFile.getFileSize() > MAX_FILE_SIZE){

request.setAttribute("err", "err");

return mapping.findForward("success");

}else{

if(formFile != null){

String dir = request.getSession(true).getServletContext().getRealPath("\\upload");

String dirs[] = dir.split("\\\\");

//文件存放的路径

String filePaht = dirs[0]+"/"+dirs[1]+"/"+dirs[2]+request.getContextPath()+"/"+itemAttachForm.getItem_id()+"/" ;

System.out.println("文件存放的地址:"+filePaht);

File f = new File(filePaht);

if(!f.exists()){

f.mkdirs();

System.out.println("文件存放的目录:"+filePaht+"创建成功!");

}

//去掉文件名的空格

String fileName = formFile.getFileName().trim().replaceAll(" ", "");

//去掉文件名存在的&字符,防止传参数出现错误

fileName = fileName.replaceAll("&", "");

fos = new FileOutputStream(filePaht+fileName);

fos.write(formFile.getFileData(),0,formFile.getFileSize());

fos.flush();

//开启连接

GetBusinessHome getBusinessHome = new GetBusinessHome();

xmxxBusinessHome = getBusinessHome.getXmxxBusinessHome();

xmxxBusiness = xmxxBusinessHome.create();

itemAttachForm.setFileName(fileName);

String sqlPath = dirs[2]+request.getContextPath()+"/"+itemAttachForm.getItem_id()+"/" +fileName;

itemAttachForm.setFilePath(sqlPath);

//保存相应的信息到数据苦中

xmxxBusiness.getDoUpload(itemAttachForm);

}

}

} catch (RuntimeException e) {

e.printStackTrace();

}catch(Exception e){

e.printStackTrace();

}finally{

if(fos != null){

fos.close();

}

}

return mapping.findForward("success");

}

}

-----------jsp ?上传查看的jsp --------<%@ page language="java" import="java.util.*" pageEncoding="gbk"%><%@ pageimport="java.io.*,java.util.*,javax.servlet.http.*,javax.servlet.*"%><%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic"%><%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%><%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%><%@ pageimport="java.sql.*,javax.naming.InitialContext,javax.sql.*,com.hymake.wygl.shared.DataModule.ItemAttachBean"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>">
<title>上传临时管理规约</title>
<meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!-- <link href="ent/main/inc/style.css" rel="stylesheet" type="text/css"> --></head><%? request.setCharacterEncoding("gbk");String entId = null;String type = null;if(request.getParameter("type") != null && request.getParameter("type").trim() !=""){type = request.getParameter("type");}else if(request.getAttribute("type") != null){type = request.getAttribute("type").toString();}if (request.getParameter("entId") != null) {entId = new String(request.getParameter("entId").getBytes("iso-8859-1"),"GBK").trim();}else if (request.getAttribute("entId") != null) {entId = request.getAttribute("entId").toString();}??%><body><div><label style="font: 15px">项目编号为:<%=entId%></label><br><label style="color: red; font: 13 px">注意:为了保证信息的完整,上传的 <B>word</B> 文件名不能包含有<B>&</B>符号!</label></div><hr><%if(request.getAttribute("err")!= null && request.getAttribute("err").equals("err")){%><div><label style="color: red; font: 13 px;"><B>上传失败:上传的文件超过10M,请分成多个文件提交上传。</B></label></div><%} %><form action="<%=path%>/doUploadItemAttach.do" method="post"enctype="multipart/form-data" onsubmit="return onSubmiFileContent();"><input type="hidden" name="item_id" value="<%=entId%>"><input type="hidden" name="type" value="<%=type%>"><input type="hidden" name="filePath" id="filePathId"><table width="100%" border="0" cellpadding="0" cellspacing="0"bgcolor="#FFFFFF"><tr><td valign="top"><table width="100%" border="0" cellpadding="4" cellspacing="0"style=" FONT-SIZE: 9pt;">临时管理规约(word):</td><td><input type="file" name="fileContent" id="fileContentid" onchange="fileURL();" onclick="fileURL();" size="15"><input type="submit" value=" 上传附件" size="20" style=" FONT-SIZE: 9pt;"><input type="button" value="关闭" onclick="window.close();" style=" FONT-SIZE: 9pt;"></td></tr></table></td></tr></table></form>
<table width="100%" border="0" cellpadding="5" cellspacing="0"bgcolor="#FFFFFF"><% ? DataSource ds = null; ? ? java.sql.Connection con=null; ?Statement stmt = null; ?String photoName =""; ?String sql = ""; ? try{ ? String dir = request.getSession(true).getServletContext().getRealPath("\\upload");String dirs[] = dir.split("\\\\");//文件存放的路径String filePaht = dirs[0]+"/"+dirs[1]+"/" ; ? ?InitialContext initCtx = new InitialContext(); ? ? ds = (DataSource)initCtx.lookup("java:/MSSQLDS"); ? ? con=ds.getConnection(); sql = "SELECT * FROM item_attach where item_id='"+entId+"' and type='"+type+"'"; System.out.print(sql); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);?? ?ResultSet rs = stmt.executeQuery(sql); ? while(rs.next()){ ? %><tr><td><form name="goodform"action="<%=path%>/ent/main/upload_attachDelete.jsp?entId=<%=entId%>&fileName=<%=new String(rs.getString("fileName").getBytes(),"gbk") %>&type=<%=type%>" method="post"><table FONT-SIZE: 9pt;"><img alt="jbos + struts1 + jsp 下传上载" src="<%=path%>/ent/main/images/icon02c.gif" width="70"height="70" /><input type="hidden" name="item_id" value="<%=entId%>"><input type="hidden" name="type" value="<%=type%>"><input type="hidden" name="fileName" value="<%=new String(rs.getString("fileName").getBytes(),"gbk") %>"></td><td align="center" style=" FONT-SIZE: 9pt;"><a href="<%=path%>/uploadItemAttachFile.do?item_id=<%=entId%>&fileName=<%=new String(rs.getString("fileName").getBytes(),"gbk") %>&type=<%=type%>"><%=new String(rs.getString("fileName").getBytes(),"gbk") %></a></td><td align="right" style=" FONT-SIZE: 9pt;"><input type="submit" value=" 删 除 "></td></tr></table></form></td></tr><% ? ?} } catch (Exception e){ ? ? ?e.printStackTrace(); ? ?} ? ?finally { ? try{ ? ? ? ? ? ? ? stmt.close(); ? ? ? ? ? ? con.close(); ?}catch(Exception e){ ?System.out.print("不能关闭数据库连接" + e); ?} ? ? ? ? } ? ? ??%></table>
</body><script type="text/javascript">??function onSubmiFileContent(){var fileContentValue = document.getElementById("fileContentid").value;if(fileContentValue == null || fileContentValue ==""){alert("请浏览选择要上传的附件(word)!");return false;}return true;}function proveDel(){if(!confirm("删除将要从新上传,是否确定删除!")){return false;}return true;}function fileURL(){document.getElementById("filePathId").value = document.getElementById("fileContentid").value;}??</script></html>
-------- 下载的 action-------
package com.hymake.wygl.ent.xmxx;
import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;
import javax.servlet.ServletOutputStream;import javax.servlet.ServletRequest;import javax.servlet.ServletResponse;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.PropertyUtils;import org.apache.struts.action.Action;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;
import com.hymake.wygl.shared.DataModule.ItemAttachBean;
/**?* @author jianght?* Jan 20, 2011?*读取附件信息?* <br>?*/public class UploadItemAttachFileAction extends Action {
@Overridepublic ActionForward execute(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response)throws Exception {InputStream ?infile = null;try {ItemAttachForm itemAttachForm = new ItemAttachForm();ItemAttachBean itemAttachBean = new ItemAttachBean();itemAttachForm = (ItemAttachForm) form;request.setAttribute("entId", itemAttachForm.getItem_id());request.setAttribute("type", itemAttachForm.getType());String fileName = new String (request.getParameter("fileName").getBytes("iso-8859-1"),"gbk");itemAttachForm.setFileName(fileName);PropertyUtils.copyProperties(itemAttachBean,form);String filePaht =null;filePaht = itemAttachBean.getDoUploadAttachFile();String dir = ?request.getSession(true).getServletContext().getRealPath("\\upload");String dirs[] = dir.split("\\\\"); filePaht = dirs[0]+"/"+dirs[1]+"/" + filePaht;? File file=new File(filePaht); if(!file.exists()){ System.out.println(filePaht + " ?文件不存在"); return null; } System.out.println("服务器存放的地址: "+ filePaht); infile = new BufferedInputStream( new FileInputStream(file)); int srcFileSize ?= infile.available();? byte[] b = new byte[srcFileSize]; response.setContentType("application/msword"); fileName = new String(fileName.getBytes("gb2312"),"ISO_8859_1"); response.setHeader("content-disposition", "attachment;filename="+fileName); response.setCharacterEncoding("gb2312"); while(infile.read(b) != -1){ response.getOutputStream().write(b); }
} catch (RuntimeException e) {e.printStackTrace();}catch(Exception e){e.printStackTrace();}finally{?? ? ? ? ? ?if ( null != infile) ?{?? ? ? ? ? ?infile.close();?? ? ? ? ? ?}??? ? ? ?}?return mapping.findForward("success");}}----------Bean 和Form
private String item_id; //项目编号private String type; //类型private String fileName; //文件名private FormFile fileContent; //文件内容private String filePath; //文件路径

读书人网 >操作系统

热点推荐