upload

* 异步上传
	1.页面文件index.jsp
	<form method="post" enctype="multipart/form-data">
	<input type="file" name=""/>
	</form>
	2.处理页面doLogin.jsp
	<%@ page import="com.jspsmart.upload.*"%>
	<%
		request.setCharacterEncoding("GBK");
		SmartUpload su=new SmartUpload();
		su.initialize(pageContext);
		su.setCharset("GBK");
		su.setAllowedFilesList("bmp,jpg,gif");//这个是在服务器端处理,不能阻止客户在客户端上传
		su.setMaxFileSize(2*1024*1024);//上传文件2M限制文件大小
		su.setTotalMaxFileSize(6*1024*1024);//限制最大的文件大小一次上传
		su.upload();
		Files files=su.getFiles();//一次上传的所有文件列表
		for(int i=0;i<files.getCount();i++){
			File file=files.getFile(i);//获取一个上传的对象
			file.getContentType();//获取文件的真实后缀名,这个即使文件是空也存在
			String ct=file.getContentType().toLowerCase().trim();
			if(ct.startsWith("image/")){//只有是图像的时候接受保存
				file.saveAs("");//新建文件夹upload在WebRoot,真正部署的时候在webapp里面的upload
				file.getFileName();//客户端穿过来的时候本机的文件名
				file.getFilePathName();//客户端的路径
				file.getFileExt();//文件的扩展名
				new java.util.Date().getTime();//获取当前的服务器端的毫秒数
				String newName="upload/"+UUID.randomUUID().toString()+"."+file.getFileExt();//通过全球唯一标识符获取新的文件名
				String newName2="upload/"+new Date().getTime()+"."+file.getFileExt();//通过上传的毫秒数来获取新文件名
				file.saveAs(newName);
				//如果上传两个的时候,客户只上传了一个的话,系统默认还是会保存空的需要
				if(file.getSize()==0)
				continue;
			}
		}
 	%>
	
	



* 异步上传照片
		(1)java
		private static final int BUFFER_SIZE=16*1024;
		private File file;
		private String fileFileName;
		private String fileFileContentType;
		private String message="你已成功上传文件";
		
		public String execute() throws Exception{
			String path=ServletActionContext.getServletContext().getRealPath("/upload/image");
			try{
				File f=this.getFile();
				if(this.getFileFileName().endsWith(".exe")){
					message="对不起,你上传的文件格式不允许!";
				}
				FileInputStream inputStream=new FileInputStream(f);
				FileOutputStream outputStream=new FileOutputStream(path+"/"+this.getFileFileName());
				byte[] buf=new byte[1024];
				int length=0;
				while((length=inputStream.read(buf))!=-1){
					outputStream.write(buf,0,length);
				}
				inputStream.close();
				outputStream.flush();
			}catch(Exception e){
				e.printStackTrace();
				message="对不起,文件上传失败!";
			}
			return SUCCESS;
		}
		
		//GET SET	
		...
		
		(2)jsp页面
				1.
				<script src="js/jquery-1.4.4.min.js"></script>
				<script src="js/ajaxfileupload.js"></script>
				2.
				<label>上传球队照片:</label>
				<input type="file" name="file" id="file" value="" ></input>
				<input type="button" οnclick="return ajaxFileUpload();" value="点我"></input>
				3.
				function ajaxFileUpload(){
				//$("#loading").ajaxComplete(function(){$(this).show()})
				$.ajaxFileUpload({
						url: "ajaxDemo",
						secureuri:false,				//一般设置为false
						fileElementId:"file",			//文件上传空间的id属性  <input type="file" id="file" name="file" />
						dataType:"json", 				//返回值类型 一般设置为json
						success: function(data,status){ 
							alert(data.message); 		//从服务器返回的json中取出message中的数据,其中message为在struts2中action中定义的成员变量
							if(typeof(data.error)!="undefined"){
								if(data.error!=""){
									alert(data.error);
								}
								else{
									alert(data.message);
								}
							}else{
														//把图片显示在页面上
								document.getElementById("pic").src="upload/image/"+data.fileFileName;
							}	
						},
						error:function(data,status,e){  //服务器响应失败处理函数
						
							alert(e);
						}
					   
				});    	
			}
		
		(3)struts.xml
			<package name="ajax" namespace="/" extends="json-default">
				<action name="ajaxDemo" class="com.szsx.huyao.AjaxDemoAction">
					<result name="success" type="json">
						<param name="contentType">text/html</param>
					</result>
					<result name="error" type="json">
						<param name="contentType">text/html</param>
					</result>
				</action>
			</package>
			
			
			


*upload
		package com.szsx.huyao.upload.action;
		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 java.util.Date;
		import org.apache.struts2.ServletActionContext;
		import com.opensymphony.xwork2.ActionSupport;


		public class UploadAction extends ActionSupport{


			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;
			private static final int BUFFER_SIZE=16*1024;
			private File myFile;
			private String contentType;
			private String fileName; //获取上传的图片的文件名
			private String imageFileName; //保存在系统中的文件名
			private String caption;
			private String message;


			private static void copy(File src,File dst){
				try{
					InputStream in=null;
					OutputStream out=null;
					try{
						in=new BufferedInputStream(new FileInputStream(src),BUFFER_SIZE);
						out=new BufferedOutputStream(new FileOutputStream(dst),BUFFER_SIZE);
						byte[] buffer=new byte[BUFFER_SIZE];
						while(in.read(buffer)>0){
							out.write(buffer);
						}
					}finally{
						if(null!=in){
							in.close();
						}
						if(null!=out){
						out.close();
						}
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
			
			/**
			 * 获取扩展名
			 * @param fileName
			 * @return
			 */
			private static String getExtention(String fileName){
				int pos=fileName.lastIndexOf(".");
				return fileName.substring(pos);
			}
			
			
			public String execute(){
				imageFileName=new Date().getTime()+getExtention(fileName);
				File imageFile=new File(ServletActionContext.getServletContext().getRealPath("upload/image")+"/"+imageFileName);
				copy(myFile,imageFile);
				return "success";
			}
			
			//GET SET	
			...


		}
		
	2.struts.xml配置
		<package name="fileUpload" extends="struts-default">
			<action name="fileUpload" class="com.szsx.huyao.upload.action.UploadAction">
				<result name="success">/team/team_info/addNewTeam.jsp</result>
			</action>
		</package> 	
	3.web.xml  		//清除缓存,帮我们进行清理在做上传文件的时候,要在web.xml中增加ActionContextCleanUp这个filter,如果不增加,会发生第一次上传取不到文件的情况
		<filter>
			<filter-name>struts-cleanup</filter-name>
			<filter-class>org.apache.struts2.dispatcher.ActionContextCleanUp</filter-class>
		</filter>
	4.jsp
		<s:form action="uploadOne" method="post" enctype="multipart/form-data">
            <s:file name="file" label="文件1"></s:file>
            <s:file name="file" label="文件2"></s:file>
            <s:file name="file" label="文件3"></s:file>
            <s:file name="file" label="文件4"></s:file>
            <s:submit label="上传"/>
        </s:form>





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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值