JQuery上传插件Uploadify并传参数(二)
Uploadify是一个Jquery框架下处理批量文件上传的插件,支持多种服务器端软件。
?
官网:http://www.uploadify.com/
文档:http://www.uploadify.com/documentation/
?
今天根据文档写了个批量上传的的功能..
?
下面直接进入主题:
?
界面效果:
?
?
?界面代码:
?
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%><%String path = request.getContextPath();%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><title>Uploadify上传</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><link rel="stylesheet" href="uploadify/uploadify.css" type="text/css"></link><script type="text/javascript" src="uploadify/jquery-1.7.2.min.js"></script><script type="text/javascript"src="uploadify/jquery.uploadify-3.1.min.js"></script><script type="text/javascript"> $(function() { $("#file_upload").uploadify({ 'height' : 27, 'width' : 80, 'buttonText' : '浏 览', 'swf' : '<%=path%>/uploadify/uploadify.swf', 'uploader' : '<%=path%>/servlet/UploadifySerlet', 'auto' : false, 'fileTypeExts' : '*.xls', 'formData' : {'userName':'','qq':''}, 'onUploadStart' : function(file) { //校验 var name=$('#userName').val(); if(name.replace(/\s/g,'') == ''){ alert("名称不能为空!"); return false; } //校验 var qq=$('#qq').val(); if(qq.replace(/\s/g,'') == ''){ alert("QQ不能为空!"); return false; } $("#file_upload").uploadify("settings", "formData", {'userName':name,'qq':qq}); //$("#file_upload").uploadify("settings", "qq", ); } });});</script></head><body>名称: <input type="text" id="userName" name="userName" value="妞见妞爱"><br> QQ: <input type="text" id="qq" name="qq" value="609865047"><br><input type="file" name="uploadify" id="file_upload" /><hr><a href="javascript:$('#file_upload').uploadify('upload','*')">开始上传</a> <a href="javascript:$('#file_upload').uploadify('cancel', '*')">取消所有上传</a> </body></html>
?
? 关于各个参数的介绍,网上也有很多。。我们也可以在 jquery.uploadify-3.1.js 中找到。
?
var settings = $.extend({// Required Settingsid : $this.attr('id'), // The ID of the DOM objectswf : 'uploadify.swf', // The path to the uploadify SWF fileuploader : 'uploadify.php', // The path to the server-side upload script// Optionsauto : true, // Automatically upload files when added to the queuebuttonClass : '', // A class name to add to the browse button DOM objectbuttonCursor : 'hand', // The cursor to use with the browse buttonbuttonImage : null, // (String or null) The path to an image to use for the Flash browse button if not using CSS to style the buttonbuttonText : 'SELECT FILES', // The text to use for the browse buttoncheckExisting : false, // The path to a server-side script that checks for existing files on the serverdebug : false, // Turn on swfUpload debugging modefileObjName : 'Filedata', // The name of the file object to use in your server-side scriptfileSizeLimit : 0, // The maximum size of an uploadable file in KB (Accepts units B KB MB GB if string, 0 for no limit)fileTypeDesc : 'All Files', // The description for file types in the browse dialogfileTypeExts : '*.*', // Allowed extensions in the browse dialog (server-side validation should also be used)height : 30, // The height of the browse buttonmethod : 'post', // The method to use when sending files to the server-side upload scriptmulti : true, // Allow multiple file selection in the browse dialogformData : {}, // An object with additional data to send to the server-side upload script with every file uploadpreventCaching : true, // Adds a random value to the Flash URL to prevent caching of it (conflicts with existing parameters)progressData : 'percentage', // ('percentage' or 'speed') Data to show in the queue item during a file uploadqueueID : false, // The ID of the DOM object to use as a file queue (without the #)queueSizeLimit : 999, // The maximum number of files that can be in the queue at one timeremoveCompleted : true, // Remove queue items from the queue when they are done uploadingremoveTimeout : 3, // The delay in seconds before removing a queue item if removeCompleted is set to truerequeueErrors : false, // Keep errored files in the queue and keep trying to upload themsuccessTimeout : 30, // The number of seconds to wait for Flash to detect the server's response after the file has finished uploadinguploadLimit : 0, // The maximum number of files you can uploadwidth : 120, // The width of the browse button
?
?上面是默认的设置。。。
?
? 服务器端代码:
?
package com.yangpan.uploadify;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.PrintWriter;import java.text.SimpleDateFormat;import java.util.Arrays;import java.util.Date;import java.util.Iterator;import java.util.List;import java.util.Random;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.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;public class UploadifySerlet extends HttpServlet {/** * */private static final long serialVersionUID = 1L;//上传文件的保存路径protected String configPath = "attached/";protected String dirTemp = "attached/temp/";protected String dirName = "file";public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { this.doPost(request, response);} public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {request.setCharacterEncoding("UTF-8");response.setContentType("text/html; charset=UTF-8");PrintWriter out = response.getWriter();//文件保存目录路径String savePath = this.getServletContext().getRealPath("/") + configPath;// 临时文件目录 String tempPath = this.getServletContext().getRealPath("/") + dirTemp;SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");String ymd = sdf.format(new Date());savePath += "/" + ymd + "/";//创建文件夹File dirFile = new File(savePath);if (!dirFile.exists()) {dirFile.mkdirs();}tempPath += "/" + ymd + "/";//创建临时文件夹File dirTempFile = new File(tempPath);if (!dirTempFile.exists()) {dirTempFile.mkdirs();}DiskFileItemFactory factory = new DiskFileItemFactory();factory.setSizeThreshold(20 * 1024 * 1024); //设定使用内存超过5M时,将产生临时文件并存储于临时目录中。 factory.setRepository(new File(tempPath)); //设定存储临时文件的目录。 ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8"); try {List items = upload.parseRequest(request);Iterator itr = items.iterator();String name = "";String qq = "";while (itr.hasNext()) {FileItem item = (FileItem) itr.next();String fileName = item.getName();long fileSize = item.getSize();if (!item.isFormField()) {String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");String newFileName = df.format(new Date()) + "_" + new Random().nextInt(1000) + "." + fileExt;try{File uploadedFile = new File(savePath, newFileName);/* * 第一种方法 * * 好处: 一目了然..简单啊... * 弊端: 这种方法会导致上传的文件大小比原来的文件要大 * * 推荐使用第二种 *///item.write(uploadedFile);//--------------------------------//第二种方法 OutputStream os = new FileOutputStream(uploadedFile); InputStream is = item.getInputStream(); byte buf[] = new byte[1024];//可以修改 1024 以提高读取速度 int length = 0; while( (length = is.read(buf)) > 0 ){ os.write(buf, 0, length); } //关闭流 os.flush(); os.close(); is.close(); System.out.println("上传成功!路径:"+savePath+"/"+newFileName); out.print("1");}catch(Exception e){e.printStackTrace();}}else {String filedName = item.getFieldName();if (filedName.equals("userName")) {name = item.getString();}else {qq = item.getString();}System.out.println("FieldName:"+filedName);System.out.println("String:"+item.getString("UTF-8"));//避免中文乱码//System.out.println("String():"+item.getString(item.getName()));System.out.println("==============="); }} } catch (FileUploadException e) {// TODO Auto-generated catch blocke.printStackTrace();}out.flush();out.close();}}
?
?
? WEB.XML
?
<servlet><servlet-name>UploadifySerlet</servlet-name><servlet-class>com.yangpan.uploadify.UploadifySerlet</servlet-class></servlet><servlet-mapping><servlet-name>UploadifySerlet</servlet-name><url-pattern>/servlet/UploadifySerlet</url-pattern></servlet-mapping>
?
?
?
? demo 下载,有问题大家可以一起讨论啊。。。。。