惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
T
Threatpost
Latest news
Latest news
N
News | PayPal Newsroom
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Help Net Security
Help Net Security
D
Darknet – Hacking Tools, Hacker News & Cyber Security
AI
AI
Simon Willison's Weblog
Simon Willison's Weblog
TaoSecurity Blog
TaoSecurity Blog
The Last Watchdog
The Last Watchdog
L
LINUX DO - 热门话题
Google DeepMind News
Google DeepMind News
T
Threat Research - Cisco Blogs
O
OpenAI News
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
The Exploit Database - CXSecurity.com
NISL@THU
NISL@THU
Application and Cybersecurity Blog
Application and Cybersecurity Blog
S
Securelist
小众软件
小众软件
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Martin Fowler
Martin Fowler
S
SegmentFault 最新的问题
Cisco Talos Blog
Cisco Talos Blog
云风的 BLOG
云风的 BLOG
AWS News Blog
AWS News Blog
GbyAI
GbyAI
N
News and Events Feed by Topic
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
美团技术团队
Engineering at Meta
Engineering at Meta
A
About on SuperTechFans
博客园 - 三生石上(FineUI控件)
S
Schneier on Security
博客园 - 聂微东
V2EX - 技术
V2EX - 技术
T
Troy Hunt's Blog
SecWiki News
SecWiki News
S
Secure Thoughts
B
Blog RSS Feed
Hugging Face - Blog
Hugging Face - Blog
WordPress大学
WordPress大学
腾讯CDC
H
Heimdal Security Blog
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Apple Machine Learning Research
Apple Machine Learning Research
月光博客
月光博客
www.infosecurity-magazine.com
www.infosecurity-magazine.com
P
Privacy International News Feed

博客园 - 樊凯

Weblogic10.3客户端jar文件 PHP5操作MySQL数据库 - 樊凯 - 博客园 Struts2拦截器 使用AppServ快速建立php运行环境 Hibernate缓存 一个关于SpringSecurity很好的参考文档 Struts2.1.6 + Spring2.5+Hibernate3.2整合 struts1.x+spring2.5+JPA(hibernate)整合 使用Apache的commons-codes加密 Spring备忘(涵盖Spring2.5) Spring备忘四(涵盖Spring2.5) Sping备忘三(涵盖Spring2.5) Spring备忘二(涵盖Spring2.5) - 樊凯 - 博客园 Spring备忘一(涵盖Spring2.5) ubuntu遇到的错误 Ubuntu命令(更新中) 异常java.lang.UnsupportedClassVersionError: Bad version number in .class file 根据ResultSetMetaData对象动态创建pojo或其集合(JDBC) 天生我牛必有用
JQuery和Struts实现Ajax文件上传
樊凯 · 2009-06-17 · via 博客园 - 樊凯

首先说下使用的框架和插件:

struts1.3   jQuery1.3   ajaxupload.3.2.js(一个JQuery的插件,实现Ajax上传的效果)

COS(O’relly的一个性能很棒的上传组件)

jsp页面:

<%@ page language="java"  pageEncoding="UTF-8"%>
<%@ include file="../../common/taglibs.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  	<script type="text/javascript" src="${basePath }/script/jquery.js"></script>
  	<script type="text/javascript" src="${basePath }/script/ajaxupload.3.2.js"></script>
    <title>Ajax文件上传示例</title>
    <style type="text/css">
    	#loading,ol{
    		font-size:14px;
    		display:none;
    		color:orange;
    		display:none;
    	}
    	ol{
    		display:block;
    	}
    </style>
	<script type="text/javascript">
		$(function(){
			
			new AjaxUpload("#fileButton",{
				action:"${basePath}/file.do?method=upload",
				autoSubmit:true,
				name:"myfile",
				onSubmit:function(file, extension){
					if (extension && /^(pdf|jpg|png|jpeg|gif)$/.test(extension))
					{
						$("#loading").html('<img src="${basePath}/images/loading.gif">');
						$("#loading").show();
						$("#fileButton").attr("disabled","disabled");
					}
					else
					{
						$("#loading").html("你所选择的文件不受系统支持");
						$("#loading").show();
						return false;
					}
				},
				onComplete:function(file, extension){
					$("#loading").html("文件上传成功");
					$("#loading").show();
					$("#fileButton").removeAttr("disabled");
				}
			});
			
			
			new Ajax_upload('#button3', {
				action: '${basePath}/file.do?method=upload',
				name: 'myfile',
				autoSubmit:true,
				onComplete : function(file, extension){
					$('<li></li>').appendTo($('.files')).text(file);
				}	
			});
		});
	</script>
  </head>
  
  <body> 
    <input type="button" value="请选择您的照片" id="fileButton"/>
    <div id="loading"><img src="${basePath}/images/loading.gif"></div>
    <hr/>
   
    <form action="#" method="post">

		<input id="button3" type="file" />
		<p>上传成功的文件有:</p>
		<ol class="files"></ol>
		<p>
			<input class="submit" type="submit" value="表单提交"/>	
		</p>

	</form>

  </body>
</html>
StrutsAction代码:
package com.kay.crm.web;

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

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 org.springframework.stereotype.Controller;

import com.kay.common.util.CosUtil;

@Controller("/file")
public class FileUploadAction extends DispatchAction {

	public ActionForward upload(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
		

		String fileName = CosUtil.upload(request);
		System.out.println(fileName);
		
		return null;
	}
}
Cos的工具类:
package com.kay.common.util;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import com.oreilly.servlet.MultipartRequest;

public class CosUtil {

	@SuppressWarnings({ "deprecation", "unchecked" })
	public static String upload(HttpServletRequest request) throws IOException
	{
		//存绝对路径
		//String filePath = "C://upload";
		//存相对路径
		String filePath = request.getRealPath("/")+"upload";
		File uploadPath = new File(filePath);
		//检查文件夹是否存在 不存在 创建一个
		if(!uploadPath.exists())
		{
			uploadPath.mkdir();
		}
		//文件最大容量 5M
		int fileMaxSize = 5*1024*1024;
	
		//文件名
		String fileName = null;
		//上传文件数
		int fileCount = 0;
		//重命名策略
		RandomFileRenamePolicy rfrp=new RandomFileRenamePolicy();
		//上传文件
		MultipartRequest mulit = new MultipartRequest(request,filePath,fileMaxSize,"UTF-8",rfrp);
		
		String userName = mulit.getParameter("userName");
		System.out.println(userName);
		
		Enumeration filesname = mulit.getFileNames();
	      while(filesname.hasMoreElements()){
	           String name = (String)filesname.nextElement();
	           fileName = mulit.getFilesystemName(name);
	           String contentType = mulit.getContentType(name);
	           
	           if(fileName!=null){
	        	   fileCount++;
	           }
	           System.out.println("文件名:" + fileName);
	           System.out.println("文件类型: " + contentType);
	           
	      }
	      System.out.println("共上传" + fileCount + "个文件!");
	      
	      return fileName;
	}
}
Cos上传组件用到的重命名策略类:
package com.kay.common.util;

import java.io.File;
import java.util.Date;

import com.oreilly.servlet.multipart.FileRenamePolicy;

public class RandomFileRenamePolicy implements FileRenamePolicy {

	public File rename(File file) {
	  String body="";
      String ext="";
      Date date = new Date();
      int pot=file.getName().lastIndexOf(".");
      if(pot!=-1){
          body= date.getTime() +"";
          ext=file.getName().substring(pot);
      }else{
          body=(new Date()).getTime()+"";
          ext="";
      }
      String newName=body+ext;
      file=new File(file.getParent(),newName);
      return file;

	}

}