SWFUpload+commons-fileupload 上传文件

说明:使用SWFUpload 上传文件,可在客户端校验文件大小,动态显示上传进度等。

SWFUpload 官网:http://www.swfupload.org/project 

SWFUpload Demo: http://demo.swfupload.org/v220/ 

// client 端

<%@page language="java" contentType="text/html;charset=utf-8"%>
<%
    String contextPath = request.getContextPath();
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Simple Upload Demo</title>
<link type="text/css" rel="stylesheet" href="simple.css"/>
<script type="text/javascript" src="<%=contextPath%>/js/swfupload.js"></script>
<script type="text/javascript" src="handlers.js"></script>
<script type="text/javascript">
var swfu;
window.onload = function () {
    swfu = new SWFUpload({
        // Flash Settings
        flash_url : "<%=contextPath%>/flash/swfupload.swf",
    
        // Backend settings
        preserve_relative_urls: true,                 // 保留相对路径不做转换
        upload_url: "<%=contextPath%>/uploadServlet", // servlet path
                 
        // Flash file settings
        file_types : "*.jpg;*.png",
        file_types_description : "Image File",
        file_size_limit : "10 MB",
        file_queue_limit : "1",
    
        // Event handler settings
        file_dialog_start_handler: fileDialogStart, // fired after selectFile is called.
        file_queued_handler : fileQueued,           // fired after file selection dialog close.
        file_queue_error_handler : fileQueueError,  // fired when file was not queued.
        file_dialog_complete_handler : fileDialogComplete,// fired when all files queued.
                 
        upload_progress_handler : uploadProgress,  // upload status
        upload_error_handler : uploadError,        // fired when upload error thrown
        upload_success_handler : uploadSuccess,    // fired when server return a 200 status
        upload_complete_handler : uploadComplete,  // fired at the end of an upload cycle
    
        // Button Settings
        button_image_url : "<%=contextPath%>/image/btnUpload.png",
        button_placeholder_id : "btnPlaceHolder",
        button_width: 61,
        button_height: 22,
        button_action: SWFUpload.BUTTON_ACTION.SELECT_FILE, // 单选

        // debug infor
        debug:false
    });
};
    </script>
</head>
<body>

<div id="uploadContent">
    <input id="txtFileName" type="text" disabled="disabled" value="" style="width:151px;"/>
    <span id="btnPlaceHolder"></span>
    <div id="uploadProgress">
        <div id="colorStatus"></div>
        <div id="percentTxt"></div>
    </div>
</div>

<input id="btnStartUpload" type="button" value="开始上传" οnclick="startUpload()" disabled="disabled" style="position:relative;left:200px;"/>

</body>
</html>

 

 // server 端

 

package org.demo.tomcat;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.FileCleanerCleanup;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileCleaningTracker;

/**
 * 
 * @author  
 * @date    2010-12-16
 * @file    org.demo.tomcat.UploadServlet.java
 */
public class UploadServlet extends HttpServlet {

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

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		
		boolean isMultipart = ServletFileUpload.isMultipartContent(req);
		if (!isMultipart){
			System.out.println(">> This wasn't a file upload request!");
			return;
		}
		
		PrintWriter out = resp.getWriter();
		
		// create factory and file cleanup tracker
		FileCleaningTracker tracker = FileCleanerCleanup.getFileCleaningTracker(getServletContext());
		File tmpDir = new File(getBaseDir() + "/upload/temp");
		DiskFileItemFactory factory = new DiskFileItemFactory(
				DiskFileItemFactory.DEFAULT_SIZE_THRESHOLD,
				tmpDir);
		factory.setFileCleaningTracker(tracker);
		
		// save upload file to disk
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> items = upload.parseRequest(req);
			String fileName = null;
			File savefile = null;
			for (FileItem item : items){
				if (!item.isFormField()){
					// 确定是文件而不是一个普通的表单字段
					fileName = item.getName();
					savefile = new File(getBaseDir() + "/upload/" + fileName);
					item.write(savefile);
					System.out.println(">> [save] " + savefile.getAbsolutePath());

					// to client info
					out.print("fileId=" + savefile.getAbsolutePath());
					out.flush();
				}
			}
		} catch (Exception e) {
			System.out.println(">> " + e.getMessage());
			throw new IOException(e.getMessage());
		}
	}
	
	/**
	 * Return the WEB-INF directory.
	 * @return
	 */
	private String getBaseDir(){
		return this.getServletContext().getRealPath("/WEB-INF");
	}
}

  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值