现在的位置: 首页 > 综合 > 正文

uploadiy3.2_Java_Servlet_多文件上传

2013年10月30日 ⁄ 综合 ⁄ 共 5737字 ⁄ 字号 评论关闭

参考:

    1, Servlet实现文件上传,可多文件上传

    2, uploadify+批量上传文件+java

    3, jquery上传插件Uploadify3.2中文详细参考手册.pdf

示例下载

    uploadify3.2_Java_Servlet_多文件.zip

一, 准备工作

参看:手工编写servlet_MS-DOS编译servlet_Servlet修改后自动载入

二, servlet 处理文件上传请求

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

import org.apache.commons.fileupload.FileItem;  
import org.apache.commons.fileupload.FileUploadException;  
import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
import org.apache.commons.fileupload.servlet.ServletFileUpload;  
/**
文件上传
上传文件存放位置:当前web应用的 upload目录
*/
public class ProcessUpload extends HttpServlet
{
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		/**/
		System.out.println("I am a serlvet to process upload!!!");
		
	
		request.setCharacterEncoding( "UTF-8" );	// 从request中取时, 以UTF-8编码解析

		// 工厂, 
		DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();

		// 获取上传文件存放的 目录 , 无则创建
		String path = request.getRealPath( "/upload" );
		System.out.println("path : " + path);

		new java.io.File( path ).mkdir();
        /** 
         * 原理 它是先存到 暂时存储室,然后在真正写到 对应目录的硬盘上,  
         * 按理来说 当上传一个文件时,其实是上传了两份,第一个是以 .tem 格式的  
         * 然后再将其真正写到 对应目录的硬盘上 
         */  
		diskFileItemFactory.setRepository( new File( path ) );
        //设置 缓存的大小,当上传文件的容量超过该缓存时,直接放到 暂时存储室  
        diskFileItemFactory.setSizeThreshold( 1024*1024 );
		

        ServletFileUpload upload = new ServletFileUpload(diskFileItemFactory); 
        try
        {
            // 可上传多个文件
            List<FileItem> list = (List<FileItem>) upload.parseRequest( request );
            
            for (FileItem item : list )
            {
                // 获取 提交表单的 属性名
                String name = item.getFieldName();

                // 字符串类 属性
                if ( item.isFormField() )
                {
                    String value = item.getString();
                    System.out.println(name + "=" + value);
                } 
                // 二进制类
                else 
                {
                    // 获取上传文件的名字                   
                    String value = item.getName(); // 1,获取路径                    
                    int start = value.lastIndexOf( "\\" );// 2,索引到最后一个反斜杠
                    String filename = value.substring( start+1 );//3, 截取(+1是去掉反斜杠) 

                    System.out.println( name + "=" + value );

                    File file = null;
                    do {  
                        // 生成文件名
                        start = filename.lastIndexOf( "." );    // 索引到最后一个点
                        filename = filename.substring( 0, start )    // 不含扩展名的文件
                                    + UUID.randomUUID().toString()  // 随机数
                                    + filename.substring( start );  // 扩展名
                        file = new File(path, filename);  
                    } while (file.exists());  

                    System.out.println( "filename=" + filename );

                    // 写到磁盘上去
                    item.write( file );

                    System.out.println( "the upload file's size:" + item.getSize() );

                }


            }

        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

	}

// -------------------
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
	{
		this.doPost(request, response);
	}
	
	public static void main(String[] args) {
		System.out.println( "I am a serlvet to process upload!" );
	}
}

三, 页面 index.html

<html>
<head>

	<title>UploadifyTest</title>

	<script src="./js/jquery-1.9.1.js" type="text/javascript"></script>
	<script src="./js/jquery.uploadify.min.js" type="text/javascript"></script>

	<link rel="stylesheet" type="text/css" href="./css/uploadify.css">
	
	<script type="text/javascript">
		$(function() {
			$("#uploadify").uploadify({
				debug			: false, 

				swf 			: 'js/uploadify.swf',	//swf文件路径
				method			: 'post',	// 提交方式
				uploader		: 'processUpload', // 服务器端处理该上传请求的程序(servlet, struts2-Action)

				preventCaching	: true,		// 加随机数到URL后,防止缓存

				buttonCursor	: 'hand',	// 上传按钮Hover时的鼠标形状
			//	buttonImage		: 'img/.....png',	// 按钮的背景图片,会覆盖文字
				buttonText		: 'select file'	, //按钮上显示的文字,默认”SELECTFILES”
				height			: 30	, // 30 px
				width			: 120	, // 120 px

				fileObjName		: 'filedata',	//文件对象名称, 即属性名
				fileSizeLimit	: 100	,		// 文件大小限制, 100 KB
				fileTypeDesc	: 'any'	,	//文件类型说明 any(*.*)
				fileTypeExts	: '*.*;*.txt',		// 允许的文件类型,分号分隔
				formData		: {'id':'1', 'name':'myFile'} , //指定上传文件附带的其他数据。也动态设置。可通过getParameter()获取
				
				multi			: true ,	// 多文件上传
				progressData	: 'speed',	// 进度显示, speed-上传速度,percentage-百分比	
				queueID			: 'fileQueue',//上传队列的DOM元素的ID号
				queueSizeLimit	: 99	,	// 队列长度
				removeCompleted : false	,	// 上传完成后是否删除队列中的对应元素
				removeTimeout	: 10	,	//上传完成后多少秒后删除队列中的进度条, 
				requeueErrors	: true,	// 上传失败后重新加入队列
				uploadLimit		: 20,	// 最多上传文件数量

				successTimeout	: 30	,//表示文件上传完成后等待服务器响应的时间。超过该时间,那么将认为上传成功。
				
				// 在文件被移除出队列时触发	
				//onCancel : function(file) { alert( 'The file ' + file.name + ' was cancelled!' ); },
				
				// 在调用cancel方法且传入参数’*’时触发
				//onClearQueue : function (queueItemCount) { alert( queueItemCount + ' files were removed from the queue!' ); },

				// 打开文件对话框 关闭时触发
				onDialogClose : function (queueData) {
								/*	alert(
										"文件对话窗口中选了几个文件:" + queueData.filesSelected + "---" +
										"队列中加了几个文件:" + queueData.filesQueued + "---" +
										"队列中被替换掉的文件数:" + queueData.filesReplaced + "---" +
										"取消掉的文件数:" + queueData.filesCancelled + "---" + 
										"上传出错的文件数:" + queueData.filesErrored
									); */
								},
				
				// 选择文件对话框打开时触发
				onDialogOpen : function () { /*alert( 'please select files' ) */ },
			
				// 没有兼容的FLASH时触发
				onFallback : function(){ alert( 'Flash was not detected!' ) },
				
				// 每次初始化一个队列时触发, 即浏览文件后, 加入一个队列
				//onInit : function (instance) { alert( 'The queue ID is ' + instance.settings.queueID ) },
			
				// 上传文件处理完成后触发(每一个文件都触发一次), 无论成功失败
				//onUploadComplete : function(file){ alert( 'The file ' + file.name + ' uploaded finished!' ) },

				// 上传文件失败触发
				onUploadError : function(file, errorCode, errorMsg, errorString){ 
                                    /*
                                    alert(
                                        file.name + ' upload failed! ' + 
                                        'errorCode: ' + errorCode +
                                        'errorMsg:' + errorMsg +
                                        'errorString:' + errorString
                                    );*/
								},
                
                // 在每一个文件上传成功后触发
                onUploadSuccess : function(file, data, response) {
                                    alert(
                                        file.name + ' is uploaded succeed!  ' +
                                        '  server-side returned data:' + data +
                                        '  response: ' + response
                                    );
                                  }

			});
		})
	</script>
</head>

<body>
	<h1>Uploadify Demo</h1>

	<p>
		<a href="javascript:$('#uploadify').uploadify('cancel','*')">clean queue</a>
	</p>
    <p>
		<a href="javascript:$('#uploadify').uploadify('cancel')">cancel first file</a>
	</p>
    <p>
		<a href="javascript:$('#uploadify').uploadify('stop', '*')">stop all files</a>
	</p>
    <p>
		<a href="javascript:$('#uploadify').uploadify('upload', '*')">start all files</a>
	</p>
	<div id="fileQueue"></div>

	<span id="uploadify"></span>

	


</body>
</html>

四, web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <servlet>
        <servlet-name>processUpload</servlet-name>
        <servlet-class>ProcessUpload</servlet-class>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>processUpload</servlet-name>
        <url-pattern>/processUpload</url-pattern>
    </servlet-mapping>

	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>
</web-app>

抱歉!评论已关闭.