在网上找到的一个附件上传功能,自己完善了一下,记录防止忘记

把该功能拿过来首先现在原来项目加上struts1.3的支持,在创建过程中选择struts1.3,在action处改为upload(这个不改也行),下面的action名称改为项目的action名称


《1》在struts-config里面写上如下配置:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">

<struts-config>
  <form-beans />
  <global-exceptions />
  <global-forwards />
   <action-mappings >
    <action
      parameter="method"
      path="/uploadFile"
      type="www.xwcms.net.struts.action.UploadFileAction"
      cancellable="true" />


  </action-mappings>
  
  <message-resources parameter="www.xwcms.net.struts.action.ApplicationResources" />
</struts-config>

《2》web.xml配置在添加配置的时候自动生成好了,不需要再多写什么

《3》下面是action的代码:

/*
 * Generated by MyEclipse Struts
 * Template path: templates/java/JavaClass.vtl
 */
package www.xwcms.net.struts.action;


import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Iterator;
import java.util.List;
import java.util.Random;


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


import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;


import sys.mvc.model.qiantai.TQaccessory;


/** 
 * MyEclipse Struts
 * Creation date: 10-06-2013
 * 
 * XDoclet definition:
 * @struts.action parameter="method" validate="true"
 */
public class UploadFileAction extends DispatchAction {

private TQaccessory tqaccessory;
private Connection con;

/**
* 简介:上传附件
* 作者:www.xwcms.net
* @throws UnsupportedEncodingException 

*/

@SuppressWarnings( { "deprecation", "unchecked" })
public ActionForward fileAdd(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws UnsupportedEncodingException {
response.setCharacterEncoding("UTF-8"); //防止返回文件名是乱码 
request.setCharacterEncoding("UTF-8");
//获取前台页面数据
String sizeLimit = request.getParameter("sizeLimit");//限制图片上传大小值

boolean backValue=false;
PrintWriter out = null;
ThreadLocal<String> returnStr = new ThreadLocal<String>();

String extName = ""; // 保存文件拓展名
String newFileName = ""; // 保存新的文件名
String ranFileName = getRandomFileName(); // 保存随机文件名
String savePath = getAbsoluteBasePath(request); // 获取项目根路径
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
savePath = savePath +"***\\"+sdf.format(new Date())+"\\"; //上传保存文件的路径
File fa=new File(savePath);
if(!fa.exists())//判断文件夹是否存在
{
fa.mkdir();
}
// 处理上传的文件
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
try {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
// 设置文件大小
fileUpload.setSizeMax(1024 * 1024 * Integer.parseInt(sizeLimit));
// 获得请求中的文件列表
List<FileItem> files = fileUpload.parseRequest(request);
// 获得迭代器
Iterator<FileItem> iterator = files.iterator();
while (iterator.hasNext()) {
FileItem item = iterator.next();
if (!item.isFormField()) {
String imgName = item.getName(); // 获得图片名称,此文件名包括路径
double fileSize = item.getSize();
double size = fileSize / 1024;
DecimalFormat df = new DecimalFormat("########.00 ");
String   imgSize= df.format(size);//获取图片大小 
if (imgName.lastIndexOf(".") >= 0) {
extName = imgName.substring(imgName.lastIndexOf(".")+1); // 获得文件的扩展名
}
returnStr.set(imgName);
newFileName = ranFileName +"."+ extName; // 文件重新命名
File fileupload = new File(savePath + newFileName);// 生成抽象文件
item.write(fileupload); // 上传图片到uploadImg文件夹



/**
* 这里可以将上传附件信息添加到数据
*/
String url = "jdbc:数据库://**.**.**.**:端口号/"
+ "数据库表名" + "?user="
+ "??" + "&password=" + "??";


try {
Class.forName("org.postgresql.Driver").newInstance();
con = DriverManager.getConnection(url);
} catch (Exception e) {
e.printStackTrace();
}

String reg = "insert into 数据库表(属性) values(?,?,?,?)";
try {
PreparedStatement pstmt = con.prepareStatement(reg);
pstmt.setString(1, 参数 );


pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
out = response.getWriter();
out.print("【"+returnStr.get()+"】" + "上传成功!");
out.flush();
out.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

return null;
}
//设置待申请的附件
public TQaccessory getTqaccessory() {
return tqaccessory;
}
public void setTqaccessory(TQaccessory tqaccessory) {
this.tqaccessory = tqaccessory;
}
/**
*  获得项目的根路径
* @param request
* @return
*/
private String getAbsoluteBasePath(HttpServletRequest request) {
return request.getSession().getServletContext().getRealPath("/");
}


/**
*  生成随机文件名:当前年月日时分秒+五位随机数
* @return
*/
private String getRandomFileName() {
//SimpleDateFormat sDateFormat;
Random r = new Random();
int rannum = (int) (r.nextDouble() * (99999 - 10000 + 1)) + 10000; // 获取随机数
//sDateFormat = new SimpleDateFormat("yyyyMMdd"); // 时间格式化的格式
// return rannum+""+new Date().getTime(); // 当前时间
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
return sdf.format(new Date())+""+rannum;
}
}


《4》以下是index.jsp代码“

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
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>My JSP 'index.jsp' starting page</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="<%=basePath%>uploadify/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=basePath%>uploadify/scripts/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<%=basePath%>uploadify/scripts/jquery.uploadify.v2.1.0.min.js"></script>
<script type="text/javascript" src="<%=basePath%>uploadify/scripts/swfobject.js"></script>
<script type="text/javascript"> 
jQuery(document).ready(function() { 
    jQuery("#fileupload").uploadify({ 
      'uploader'       : '<%=basePath%>uploadify/scripts/uploadify.swf',
      'script'         : 'uploadFile.do',
      'method'         : 'GET',
      'scriptData'     : {'method':'fileAdd'},
      'cancelImg'      : '<%=basePath%>uploadify/scripts/cancel.png',
      'queueID'        : 'fileQueue', //和存放队列的DIV的id一致 
      'fileDataName'   : 'fileupload', //和以下input的name属性一致 
      'auto'           : false, //是否自动开始 
      'multi'          : true, //是否支持多文件上传 
      'buttonImg'      : '<%=basePath%>uploadify/scripts/liulan.gif',
      'buttonText'     : 'UPLOAD', //按钮上的文字 
      'width'          : 60,
      'height'         : 32,
      'wmode'          : 'transparent',
      'simUploadLimit' : 1, //一次同步上传的文件数目 
      'sizeLimit'      : 1024*1024*5, //设置单个文件大小限制 
      'queueSizeLimit' : 20, //队列中同时存在的文件个数限制 
      'fileDesc'       : '支持格式:jpg/gif/jpeg/png/bmp/rar/zip/doc', //如果配置了以下的'fileExt'属性,那么这个属性是必须的 
      'fileExt'        : '*.jpg;*.gif;*.jpeg;*.png;*.bmp;*.rar;*.zip;*.doc',//允许的格式  
      'onSelectOnce'   : function(event,data) {
                 document.getElementById("sc").style.display="block";
                 document.getElementById("qx").style.display="block";
  },//选中事件
  'onAllComplete'  : function(event,data) {
  //alert("图片上传成功!");
  },//全部上传完成事件        
onComplete: function (event, queueID, fileObj, response, data) { 
jQuery('<li></li>').appendTo('.files').html(response); 
}, 
onError: function(event, queueID, fileObj) { 
        alert("文件:" + fileObj.name + "上传失败"); 
  }

       }); 

   }); 


</script>
<script type="text/javascript">
    
function uploadifyUpload(){ 
       var sizeLimit=5;  
  jQuery("#fileupload").uploadifySettings('scriptData',{'method':'fileAdd','sizeLimit':sizeLimit});  
  jQuery('#fileupload').uploadifyUpload(); 

</script>
</head>


<body>
<table width="100%" border="0" cellspacing="0" cellpadding="0">

<tr>
  <td>
上传图片:
</td>
<td>
<table width="50%">
<tr>
<td width="80">
<input type="file" name="fileupload" id="fileupload" />
</td>
<td width="370">
<div id="fileQueue" style="border: 0px #FF0000 solid;">
<ol class=files></ol>
</div>
</td>
<td width="70" id="sc" style="display: none;">
<div id="uploadDiv">
<a href="javaScript:uploadifyUpload()"><img src="<%=basePath%>uploadify/scripts/upload.gif" border="0" /></a>
</div>
</td>
<td id="qx" style="display: none;">
<div id="cancelAllDiv">
<img
src="<%=basePath%>uploadify/scripts/cancelAll.gif"
border="0"
οnclick="jQuery('#fileupload').uploadifyClearQueue()" />
</div>
</td>
</tr>


</table>
</td>
</tr>
</table>
</body>
 
</html>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值