【文件上传】uploadify插件配合java的使用,可以图片,按照步骤可以复制粘贴直接运行,2017年

一点说明:此代码没有对重复的图片进行处理,也就是说,同一张图片选择多次就可以传入多次,如果单独上传图片的要注意这一点;因为这个程序本身是上传文件用的,重复的文件理论上是可以上传的,没什么毛病,几个点击按钮的超链接特别丑,自己用css搞起来;

直奔主题

第一步,去uploadify官网下载插件,uplaodify.zip,去apache下载上传需要的jar包:commons-fileupload-1.3.3.jar,commons-io-2.5.jar,commons-codec-1.10.jar,版本不限,百度都特别容易找到,直接百度commons-fileupload等。。。


第二步:建立web项目:结构如下:对应位置,放进去,记得看下jar包有么有buildpath进去


第三步:各个位置的代码:

首先是 web.xml里面的内容,建议直接复制粘贴,注意里面servlet的class对应好upload类

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    
  <servlet>
    <servlet-name>upload</servlet-name>
    <servlet-class>com.xxx.upload.Upload</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>upload</servlet-name>
    <url-pattern>/servlet/Upload</url-pattern>
  </servlet-mapping>
 
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

其次是jsp,里面包含了js代码,几个alert弹窗着实烦人,尝试成功以后,把alert全部注释掉好了

<%@ page language="java" contentType="text/html; charset=utf-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>

<title>Upload</title>
 
<!--装载文件-->
<link href="<%=request.getContextPath()%>/css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="<%=request.getContextPath()%>/uploadify/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/uploadify/jquery.uploadify.min.js"></script>

<!--ready事件-->
<script type="text/javascript">
    $(document).ready(function() {
        $("#uploadify").uploadify({
            'uploader' : 'servlet/Upload',
            'swf' : 'uploadify/uploadify.swf',
            'cancelImg' : 'img/uploadify-cancel.png',
            'folder' : 'uploads',//您想将文件保存到的路径
            'queueID' : 'fileQueue',//与下面的id对应
            'queueSizeLimit' : 5,
            'fileDesc' : 'rar文件或zip文件',
            'fileExt' : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc
            'auto' : false,
            'multi' : true,
            'simUploadLimit' : 2,
            'buttonText' : '选择文件',
           	'onDialogOpen' : function() {//当选择文件对话框打开时触发
           		alert( 'Open!');
           	},
           	'onSelect' : function(file) {//当每个文件添加至队列后触发
           		alert( 'id: ' + file.id
           				+ ' - 索引: ' + file.index
           				+ ' - 文件名: ' + file.name
           				+ ' - 文件大小: ' + file.size
           				+ ' - 类型: ' + file.type
           				+ ' - 创建日期: ' + file.creationdate
           				+ ' - 修改日期: ' + file.modificationdate
           				+ ' - 文件状态: ' + file.filestatus);
           	},
           	'onSelectError' : function(file,errorCode,errorMsg) {//当文件选定发生错误时触发
           		alert( 'id: ' + file.id
           			+ ' - 索引: ' + file.index
           			+ ' - 文件名: ' + file.name
         			+ ' - 文件大小: ' + file.size
           			+ ' - 类型: ' + file.type
           			+ ' - 创建日期: ' + file.creationdate
           			+ ' - 修改日期: ' + file.modificationdate
           			+ ' - 文件状态: ' + file.filestatus
           			+ ' - 错误代码: ' + errorCode
           			+ ' - 错误信息: ' + errorMsg);
           	},
           	'onDialogClose' : function(swfuploadifyQueue) {//当文件选择对话框关闭时触发
				if( swfuploadifyQueue.filesErrored > 0 ){
          			alert( '添加至队列时有'
						+swfuploadifyQueue.filesErrored
	           			+'个文件发生错误n'
	           			+'错误信息:'
	           			+swfuploadifyQueue.errorMsg
	           			+'n选定的文件数:'
	           			+swfuploadifyQueue.filesSelected
	           			+'n成功添加至队列的文件数:'
	           			+swfuploadifyQueue.filesQueued
	           			+'n队列中的总文件数量:'
	       				+swfuploadifyQueue.queueLength);
           		}
           	},
           	'onQueueComplete' : function(stats) {//当队列中的所有文件全部完成上传时触发
           		alert( '成功上传的文件数: ' + stats.successful_uploads
           			+ ' - 上传出错的文件数: ' + stats.upload_errors
           			+ ' - 取消上传的文件数: ' + stats.upload_cancelled
           			+ ' - 出错的文件数' + stats.queue_errors);
           	},
           	'onUploadComplete' : function(file,swfuploadifyQueue) {//队列中的每个文件上传完成时触发一次
           		alert( 'id: ' + file.id
           			+ ' - 索引: ' + file.index
           			+ ' - 文件名: ' + file.name
           			+ ' - 文件大小: ' + file.size
           			+ ' - 类型: ' + file.type
           			+ ' - 创建日期: ' + file.creationdate
           			+ ' - 修改日期: ' + file.modificationdate
           			+ ' - 文件状态: ' + file.filestatus);
           	},
           	'onUploadError' : function(file,errorCode,errorMsg,errorString,swfuploadifyQueue) {//上传文件出错是触发(每个出错文件触发一次)
           		alert( 'id: ' + file.id
           			+ ' - 索引: ' + file.index
           			+ ' - 文件名: ' + file.name
           			+ ' - 文件大小: ' + file.size
           			+ ' - 类型: ' + file.type
           			+ ' - 创建日期: ' + file.creationdate
           			+ ' - 修改日期: ' + file.modificationdate
           			+ ' - 文件状态: ' + file.filestatus
           			+ ' - 错误代码: ' + errorCode
           			+ ' - 错误描述: ' + errorMsg
           			+ ' - 简要错误描述: ' + errorString);
           	},
           	'onUploadProgress' : function(file,fileBytesLoaded,fileTotalBytes,queueBytesLoaded,swfuploadifyQueueUploadSize) {//上传进度发生变更时触发
           		alert( 'id: ' + file.id
           			+ ' - 索引: ' + file.index
           			+ ' - 文件名: ' + file.name
           			+ ' - 文件大小: ' + file.size
           			+ ' - 类型: ' + file.type
           			+ ' - 创建日期: ' + file.creationdate
           			+ ' - 修改日期: ' + file.modificationdate
           			+ ' - 文件状态: ' + file.filestatus
           			+ ' - 当前文件已上传: ' + fileBytesLoaded
           			+ ' - 当前文件大小: ' + fileTotalBytes
           			+ ' - 队列已上传: ' + queueBytesLoaded
           			+ ' - 队列大小: ' + swfuploadifyQueueUploadSize);
           	},
           	'onUploadStart': function(file) {//上传开始时触发(每个文件触发一次)
           		alert( 'id: ' + file.id
           			+ ' - 索引: ' + file.index
           			+ ' - 文件名: ' + file.name
           			+ ' - 文件大小: ' + file.size
           			+ ' - 类型: ' + file.type
           			+ ' - 创建日期: ' + file.creationdate
           			+ ' - 修改日期: ' + file.modificationdate
           			+ ' - 文件状态: ' + file.filestatus );
           	},
           	'onUploadSuccess' : function(file,data,response) {//上传完成时触发(每个文件触发一次)
           		alert( 'id: ' + file.id
           			+ ' - 索引: ' + file.index
           			+ ' - 文件名: ' + file.name
           			+ ' - 文件大小: ' + file.size
           			+ ' - 类型: ' + file.type
           			+ ' - 创建日期: ' + file.creationdate
           			+ ' - 修改日期: ' + file.modificationdate
           			+ ' - 文件状态: ' + file.filestatus
           			+ ' - 服务器端消息: ' + data
           			+ ' - 是否上传成功: ' + response);
           	}
        });
    });
</script>
</head>
 
<body>
    <div id="fileQueue"></div>
    <input type="file" name="uploadify" id="uploadify" />
    <p>
    	<!-- 上传第一个未上传的文件 -->
      	<a href="javascript:$('#uploadify').uploadify('upload')">上传</a>
      	<!-- 取消第一个未取消的文件 -->
        <a href="javascript:$('#uploadify').uploadify('cancel')">取消上传</a>
        <a href="javascript:$('#uploadify').uploadify('upload','*')">开始上传所有文件</a> 
        <a href="javascript:$('#uploadify').uploadify('cancel','*')">取消所有上传</a>
    </p>
</body>
</html>

最后,Java后台代码

package com.xxx.upload;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

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;

@SuppressWarnings("serial")
public class Upload extends HttpServlet {

	@SuppressWarnings("unchecked")
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		String savePath = this.getServletConfig().getServletContext().getRealPath("");
		savePath = savePath + "/uploads/";

		File f1 = new File(savePath);
		System.out.println(savePath);
		if (!f1.exists()) {
			f1.mkdirs();
		}
		DiskFileItemFactory fac = new DiskFileItemFactory();
		ServletFileUpload upload = new ServletFileUpload(fac);
		upload.setHeaderEncoding("utf-8");
		List fileList = null;
		try {
			fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			return;
		}
		Iterator<FileItem> it = fileList.iterator();
		String name = "";
		String extName = "";
		while (it.hasNext()) {
			FileItem item = it.next();
			if (!item.isFormField()) {
				name = item.getName();
				long size = item.getSize();
				String type = item.getContentType();
				System.out.println(size + " " + type);
				if (name == null || name.trim().equals("")) {
					continue;
				}
				// 扩展名格式:
				if (name.lastIndexOf(".") >= 0) {
					extName = name.substring(name.lastIndexOf("."));
				}
				File file = null;
				do {
					// 生成文件名:
					name = UUID.randomUUID().toString();
					file = new File(savePath + name + extName);
				} while (file.exists());
				File saveFile = new File(savePath + name + extName);
				try {
					item.write(saveFile);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		response.getWriter().print(name + extName);
	}
}


至此结束,可以用服务器发布跑起来试试,应该没什么问题

最后去服务器下面去检查,文件是否已经上传成功!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值