解决swfupload items size=0

swfupload v2.2 或者2.5在struts1+spring+hibernate项目中 一开始的时候能上传文件,后来就不行了,让我很纳闷,网上也找了很多资料 ,但是没有提到我遇到的这个问题,

jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@ taglib uri="http://java.sun.com/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%
  String path = request.getContextPath();
  String jsessionid=request.getSession().getId();
 
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
   
    <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="<%=path %>/swfupload/default.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=path %>/swfupload/swfupload.js"></script>
<script type="text/javascript" src="<%=path %>/swfupload/swfupload.queue.js"></script>
<script type="text/javascript" src="<%=path %>/swfupload/fileprogress.js"></script>
<script type="text/javascript" src="<%=path %>/swfupload/handlers.js"></script>
<!-- <link rel="stylesheet" type="text/css" href="<%=path %>/fileui/easyui.css">

--><link rel="stylesheet" type="text/css" href="<%=path %>/fileui/icon.css">
<link rel="stylesheet" type="text/css" href="<%=path %>/fileui/demo.css">
<script type="text/javascript" src="<%=path %>/fileui/jquery-1.8.0.min.js"></script>
<!-- 用于文件列表数据展示 -->
<script type="text/javascript" src="<%=path %>/fileui/js/jquery.pagination.js"></script>
<link type="text/css" href="<%=path %>/fileui/css/default.css" rel="stylesheet" />
<link type="text/css" href="<%=path %>/fileui/css/flexslider.min.css?v=3" rel="stylesheet" />
<link rel="stylesheet" href="<%=path %>/fileui/css/pagination.css" />
<script type="text/javascript">
var swfu;

SWFUpload.onload = function () {
var settings = {
flash_url : "<%=path %>/swfupload/swfupload.swf",
flash9_url : "<%=path%>/swfupload/swfupload_fp9.swf",
//upload_url: "<%=path%>/acl/FileManagerAction.do;jsessionid=<%=jsessionid%>?method=uploadAction",
upload_url: "<%=path%>/servlet/UploadServlet",

post_params: {
"PHPSESSID" : "NONEgfggggg",
"HELLO-WORLD" : "Here I Am",
".what" : "OKAY"
},
file_size_limit : "100 MB",
file_types : "*.*",
file_types_description : "All Files",
file_upload_limit : 100,
file_queue_limit : 0,
custom_settings : {
progressTarget : "fsUploadProgress",
cancelButtonId : "btnCancel"
},
debug: false,

// Button Settings
button_image_url : "<%=path %>/swfupload/XPButtonUploadText_61x22.png",
button_placeholder_id : "spanButtonPlaceholder",
button_width: 61,
button_height: 22,

// The event handler functions are defined in handlers.js
swfupload_preload_handler : swfUploadPreLoad,
swfupload_load_failed_handler : swfUploadLoadFailed,
swfupload_loaded_handler : swfUploadLoaded,
file_queued_handler : fileQueued,
file_queue_error_handler : fileQueueError,
file_dialog_complete_handler : fileDialogComplete,
upload_start_handler : uploadStart,
upload_progress_handler : uploadProgress,
upload_error_handler : uploadError,
upload_success_handler : uploadSuccess,
upload_complete_handler : uploadComplete,
queue_complete_handler : queueComplete // Queue plugin event

};

swfu = new SWFUpload(settings);
}


</script>

<script>
var json ='${fileslist}';

$(function(){
var jsonData = eval(json);
$.each(jsonData,function(i,n){
$("#Searchresult").append("<li><a href='<%=path %>/"+n.filepath+"/"+n.newfilename+"'>"+n.filename+"</a><br />"+n.filesize+"</li>"); 
});
var num_entries = $("#Searchresult li").length;
var showCount = 10;
$("#total").html("一共有 "+num_entries+" 条数据 每页显示"+showCount+"条");
var initPagination = function() {

// 创建分页
$("#Pagination").pagination(num_entries, {
num_edge_entries: 1, //边缘页数
num_display_entries: 6, //主体页数
callback: pageselectCallback,
items_per_page:showCount //每页显示1项
});
}();
function pageselectCallback(page_index, jq){
var max_elem = Math.min((page_index+1) *showCount, num_entries);
$("#htcList").html("");
for(var i=page_index*showCount;i<max_elem;i++){
var new_content = $("#Searchresult li:eq("+i+")").clone();
$("#htcList").append(new_content); //装载对应分页的内容
}
return false;
}
});


//全选
function ckall(ck){
var isAll=ck.checked;
if(isAll){
for(var i=0;i<sysFilesForm.length;i++){
if(sysFilesForm.elements[i].type=='checkbox' && sysFilesForm.elements[i].name=='userCheck'){
sysFilesForm.elements[i].checked=true;
}
}
}else{
for(var i=0;i<sysFilesForm.length;i++){
if(sysFilesForm.elements[i].type=='checkbox' && sysFilesForm.elements[i].name=='userCheck'){
sysFilesForm.elements[i].checked=false;
}
}
  }
}

function del(){
alert('批量删除');
}



</script>
  </head>
 
  <body>
    <div id="header">
<h1 id="logo">文件上传</h1>
<div id="version"></div>
</div>

<div id="content">

<h2>上传状态栏</h2>
<form id="form1" action="<%=path%>/acl/FileManagerAction.do;jsessionid=<%=jsessionid%>?method=uploadAction" method="post" enctype="multipart/form-data">
<div id="divSWFUploadUI">
<div class="fieldset  flash" id="fsUploadProgress">
<span class="legend">上传   队列</span>
</div>
<p id="divStatus">0 Files Uploaded</p>
<p>
<span id="spanButtonPlaceholder"></span>
<input id="btnCancel" type="button" value="Cancel All Uploads" disabled="disabled" style="margin-left: 2px; height: 22px; font-size: 8pt;" />
<br />
</p>
</div>
<noscript>
<div style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px;">
We're sorry.   could not load.  You must have JavaScript enabled to enjoy SWFUpload.
</div>
</noscript>
<div id="divLoadingContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
is loading. Please wait a moment...
</div>
<div id="divLongLoading" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
is taking a long time to load or the load has failed.  Please make sure that the Flash Plugin is enabled and that a working version of the Adobe Flash Player is installed.
</div>
<div id="divAlternateContent" class="content" style="background-color: #FFFF66; border-top: solid 4px #FF9966; border-bottom: solid 4px #FF9966; margin: 10px 25px; padding: 10px 15px; display: none;">
We're sorry.   could not load.  You may need to install or upgrade Flash Player.
Visit the <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash">Adobe website</a> to get the Flash Player.
</div>
</form>
</div>

<div class="demo-info">
<div class="demo-tip icon-tip"></div>
<div>提示:</div>
</div>

<div style="margin:10px 0;">
<a href="#" class="easyui-linkbutton" οnclick="open1()">打开</a>
<a href="#" class="easyui-linkbutton" οnclick="close1()">关闭</a>
<a href="#" class="easyui-linkbutton" οnclick="del()">删除</a>
<!-- <a href="#" class="easyui-linkbutton" οnclick="load1()">刷新</a> -->

</div>



<bean:define id="basePage" name="sysFilesForm" />
<html:form action="/acl/FileManagerAction.do" method="post">

<div class="clear"></div>
<div id="model">
<div class="title"><h2>数据列表</h2><a id="total"></a></div>
<div class="clear"></div><ul id="htcList">
</ul>

<div class="clear"></div>
<div id="Pagination" class="pagination"><!-- 这里显示分页 --></div>
<ul id="Searchresult" style="display:none;">
</ul>
</div>
</html:form>

  </body>
</html>


-----------------------------------------------------------------------------------------


strtus1 后台代码:
public ActionForward uploadAction(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
// System.out.println("xxx");
SysFilesForm sysFilesForm = (SysFilesForm) form;
ISysFilesService sysFilesService = ServiceLoader.getSysFilesService();
try {

request.setCharacterEncoding("UTF-8");
HttpSession session = request.getSession();
session.setAttribute("SESSIONID", session.getId());
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<?> items = upload.parseRequest(request);
System.out.println("request:" + request.getParameter("PHPSESSID"));

Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String now = df.format(date);
UserInfo user = (UserInfo) session.getAttribute(UserInfo.USERINFO);
Iterator<?> iter = items.iterator();

while (iter.hasNext()) {
System.out.println(" 进来了");
FileItem item = (FileItem) iter.next();

String fileNames = item.getName();
System.out.println(fileNames);
SysFiles sf = new SysFiles();
if (item.isFormField()) { // 判断是否为普通表单域,还是文件上传表单域。

/*
* String name = item.getFieldName(); String value =
* item.getString(); System.out.println("name = " + name);
* System.out.println("value = " + value);
* System.out.println("/r/n");
*/
} else {
String fieldName = item.getFieldName();

String fileName = item.getName();
System.out.println("文件类型   "
+ fileName.substring(fileName.lastIndexOf('.') + 1,
fileName.length()));
// boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
getListInSession(request).add(fileName);
getListInSession(request).add(UUID.randomUUID());

// String[] str=fieldName.split("\\.");
// int l=str.length-1;
// System.out.println("文件类型   "+str[l]);
//
System.out.println("fieldName = " + fieldName);
System.out.println("fileName = " + fileName);
// System.out.println("文件存储路径   "+request.getRealPath("/")+"uploadfile/");
// 路径 D:\Program
// Files\apache-tomcat-6.0.18\webapps\rockontrol_oa\UploadFiles\2009042991039312\
String filePath = this.getServlet().getServletContext()
.getRealPath("/")
+ "Files/";
File savePath = new File(filePath);
if (!savePath.exists()) { // 判断是否存在存放目录文件夹
savePath.mkdir();
savePath.createNewFile();
}

item.write(new File(filePath + now + "_" + fileName));

sf.setFilename(fileName);
sf.setFilepath("Files");
// 1mb=1024kb
// 1kb=1024byte(b)
long sizea = item.getSize(); // 上传文件大小
System.out.println("最初的文件大小: " + sizea);
double sizeb = new Double(sizea);
double sizec = sizeb / 1024 / 1024;
String parten = "#.#";
DecimalFormat decimal = new DecimalFormat(parten);
String str = decimal.format(sizeb / 1024 / 1024);
String size = String.valueOf((str)) + "MB";
if (sizec < 1) {
sf.setFilesize(sizea / 1024 + "KB");
} else {
sf.setFilesize(size);
}
System.out.println(item.getName());

// request.getRealPath("/")
// System.out.println("类型:------------"+request.getContentType());FileTypeJudge.getType
sf.setFiletype(FileTypeJudge.getType(
request.getRealPath("/") + "Files/" + now + "_"
+ fileName).toString());
sf.setNewfilename(now + "_" + fileName);
sf.setTime(new Date());
sf.setUploaduser(user.getYhdm());
int id = sysFilesService.save(sf);
if (id <= 0) {
System.out.println(fileName + "保存失败");
log.error(fileName + "保存失败");
} else {
System.out.println(fileName + "保存成功");
}
}
}
System.out.println("-------- final--------");
} catch (Exception ex) {
ex.printStackTrace();
}

return null;
// return findForwardCommon(mapping, form, "index");
}


public ActionForward getResult(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
List list =  getListInSession(request);
request.getSession().removeAttribute("_result");

response.setCharacterEncoding("utf-8");
response.getWriter().print(list);
response.flushBuffer();

return null;
}

public List getListInSession(HttpServletRequest request) {
List result = (List) request.getSession().getAttribute("_result");
if (result == null) {
result = new ArrayList();
request.getSession().setAttribute("_result", result);
}
return result;

}


strtuts1 xml:
<action path="/acl/FileManagerAction" type="com.sunland.action.acl.FileManagerAction"
name="sysFilesForm" scope="request" parameter="method">
<forward name="index" path="/WEB-INF/webpages/file/filemanager.jsp"
redirect="false" />

</action>


web.xml里涉及strtus1的:
<!-- Struts的配置 -->
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>org.apache.struts.action.ActionServlet</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>2</param-value>
</init-param>
<init-param>
<param-name>validate</param-name>
<param-value>true</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>


网上看到struts2遇到这个问题的解决办法是过滤器里把/*改成 *.action
这个我这个虽然是strtus1但是我应该也没有哪里做了全路径拦截

解决办法

把访问strustaction类改成访问servelt
不访问 strtus的action、

我的servelet是这样写的,当然里面有一些涉及数据库的操作 遇到同样问题的人只要参考文件操作的代码就好了

package com.sunland.servelet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.DefaultFileItemFactory;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;

import com.sunland.po.SysFiles;
import com.sunland.service.ISysFilesService;
import com.sunland.service.ServiceLoader;
import com.sunland.util.FileTypeJudge;
import com.sunland.util.UserInfo;

public class UploadFile extends HttpServlet {

/**
*
*/
private static final long serialVersionUID = 1L;

public UploadFile() {
super();
}

public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
ISysFilesService sysFilesService = ServiceLoader.getSysFilesService();
HttpSession session = request.getSession();
session.setAttribute("SESSIONID", session.getId());
UserInfo user = (UserInfo) session.getAttribute(UserInfo.USERINFO);
session.setAttribute("SESSIONID", session.getId());
FileItemFactory factory = new DefaultFileItemFactory();
FileUpload upload = new FileUpload(factory);
Iterator items;
Date date = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String now = df.format(date);
try {
items = upload.parseRequest(request).iterator();
while (items.hasNext()) {
FileItem item = (FileItem) items.next();
if (!item.isFormField()) {
String name = item.getName();
String filetype = name.substring(name.lastIndexOf("."));
//String name = System.currentTimeMillis()+filetype;
// System.out.println(name+"--"+new String(name.getBytes("GBK"),"UTF-8"));
String realpath = request.getRealPath("/Files");
String path = realpath + File.separatorChar +now + "_" + name;
File file = new File(path);
if (!file.exists()) {
File file1 = new File(realpath);
file1.mkdirs();
file.createNewFile();
}else{

file.createNewFile();
}
item.write(file);
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
PrintWriter out = response.getWriter();
out.print("<font size='2'>上传的文件为:" + name + "<br>");
out.print("保存的地址为:" + path + "</font>");

SysFiles sf = new SysFiles();
sf.setFilename(name);
sf.setFilepath("Files");
// 1mb=1024kb
// 1kb=1024byte(b)
long sizea = item.getSize(); // 上传文件大小
System.out.println("最初的文件大小: " + sizea);
double sizeb = new Double(sizea);
double sizec = sizeb / 1024 / 1024;
String parten = "#.#";
DecimalFormat decimal = new DecimalFormat(parten);
String str = decimal.format(sizeb / 1024 / 1024);
String size = String.valueOf((str)) + "MB";
if (sizec < 1) {
sf.setFilesize(sizea / 1024 + "KB");
} else {
sf.setFilesize(size);
}
System.out.println(item.getName());

// request.getRealPath("/")
// System.out.println("类型:------------"+request.getContentType());FileTypeJudge.getType
sf.setFiletype(FileTypeJudge.getType(
request.getRealPath("/") + "Files/" + now + "_"
+ name).toString());
sf.setNewfilename(now + "_" + name);
sf.setTime(new Date());
sf.setUploaduser(user.getYhdm());
int id = sysFilesService.save(sf);
if (id <= 0) {
System.out.println(name + "保存失败");
//log.error(name + "保存失败");
} else {
System.out.println(name + "保存成功");
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}

public void init() throws ServletException {
}

}

 

 

servlet的web.xml配置 很简单

<!-- 文件批量上传 start -->
 <servlet>
  <description>file upload</description>
  <display-name>file upload</display-name>
  <servlet-name>UploadServlet</servlet-name>
  <servlet-class>com.sunland.servelet.UploadFile</servlet-class>
 </servlet>

 <servlet-mapping>
  <servlet-name>UploadServlet</servlet-name>
  <url-pattern>/servlet/UploadServlet</url-pattern>
 </servlet-mapping>
 <!-- 文件批量上传 end -->

 

这样swfupload的就可以上传了 另外我改了几个 官网的php例子,可以上传批量文件,文件名称是swfobjectdemo,里面的改了可以上传,其他的没改道理一样把upload.php拷贝过去就好了,官网下载下来的是没有保存文件的,有兴趣的朋友可以下载学习。版本是最新的swfupload v2.5

 

另外这里放了一个 纯servlet上的例子 这是网上找的,你们可以参考

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值