您的位置:首页 > Web前端 > JQuery

jquery插件 jsp+servlet+uploadify3.1 文件上传

2016-12-29 19:01 627 查看
网络上很多的例子虽然说是3.1版本的,但是调用方法都是老版本的,跑不起来,经过查看doc,下面的例子可以在tomcat中正常运行。

index.jsp

[html] view plain copy print?<%@ page language=“java” contentType=“text/html; charset=utf-8”%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + ”://”
+ request.getServerName() + ”:” + request.getServerPort()
+ path + ”/”;
%>
<!DOCTYPE HTML PUBLIC ”-//W3C//DTD HTML 4.01 Transitional//EN”>
<html>
<head>
<base href=“<%=basePath%>”>

<title>文件上传</title>

<link href=“css/uploadify.css” rel=“stylesheet” type=“text/css” />
<script type=“text/javascript” src=“scripts/jquery-1.7.2.min.js”></script>
<script type=“text/javascript” src=“scripts/jquery.uploadify-3.1.min.js”></script>
<script type=“text/javascript”>
(document).ready(function() {  </span></li><li class=""><span>     $("#uploadify").uploadify({  </span></li><li class="alt"><span>                    'auto'           : false,  </span></li><li class=""><span>                    'swf'            : '<span class="tag"><</span><span>%=path%</span><span class="tag">></span><span>/scripts/uploadify.swf',  </span></span></li><li class="alt"><span>                    'uploader'       : '<span class="tag"><</span><span>%=path%</span><span class="tag">></span><span>/scripts/uploadify',//后台处理的请求  </span></span></li><li class=""><span>                    'queueID'        : 'fileQueue',//与下面的id对应  </span></li><li class="alt"><span>                    'queueSizeLimit' :1,  </span></li><li class=""><span>                    'fileTypeDesc'   :&
4000
amp;nbsp;'rar文件或zip文件',  </span></li><li class="alt"><span>                    'fileTypeExts'   : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc  </span></li><li class=""><span>                    'multi'          : true,  </span></li><li class="alt"><span>                    'buttonText'     : '上传'  </span></li><li class=""><span>     });  </span></li><li class="alt"><span>    });  </span></li><li class=""><span>    <span class="tag"></</span><span class="tag-name">script</span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>     <span class="tag"></</span><span class="tag-name">head</span><span class="tag">></span><span>  </span></span></li><li class=""><span>    <span class="tag"><</span><span class="tag-name">body</span><span class="tag">></span><span>  </span></span></li><li class="alt"><span>            <span class="tag"><</span><span class="tag-name">div</span><span> </span><span class="attribute">id</span><span>=</span><span class="attribute-value">"fileQueue"</span><span class="tag">></span><span class="tag"></</span><span class="tag-name">div</span><span class="tag">></span><span>  </span></span></li><li class=""><span>            <span class="tag"><</span><span class="tag-name">input</span><span> </span><span class="attribute">type</span><span>=</span><span class="attribute-value">"file"</span><span> </span><span class="attribute">name</span><span>=</span><span class="attribute-value">"uploadify"</span><span> </span><span class="attribute">id</span><span>=</span><span class="attribute-value">"uploadify"</span><span> </span><span class="tag">/></span><span>  </span></span></li><li class="alt"><span>            <span class="tag"><</span><span class="tag-name">p</span><span class="tag">></span><span>  </span></span></li><li class=""><span>                <span class="tag"><</span><span class="tag-name">a</span><span> </span><span class="attribute">href</span><span>=</span><span class="attribute-value">"javascript:(‘#uploadify’).uploadify(‘upload’)”>开始上传</a>
<a href=“javascript:$(‘#uploadify’).uplaodify(‘cancel’,’*’)”>取消上传</a>
</p>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>文件上传</title>

<link href="css/uploadify.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="scripts/jquery.uploadify-3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#uploadify").uploadify({
'auto'           : false,
'swf'            : '<%=path%>/scripts/uploadify.swf',
'uploader'       : '<%=path%>/scripts/uploadify',//后台处理的请求
'queueID'        : 'fileQueue',//与下面的id对应
'queueSizeLimit' :1,
'fileTypeDesc'   : 'rar文件或zip文件',
'fileTypeExts'   : '*.rar;*.zip', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc
'multi'          : true,
'buttonText'     : '上传'
});
});
</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').uplaodify('cancel','*')">取消上传</a>
</p>
</body>
</html>


servlet: Uploadify.java

[java] view plain copy print?package com.rh.core.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
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.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class Uploadify extends HttpServlet{
private static final long serialVersionUID = 1L;

/**
* 实现多文件的同时上传
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

//设置接收的编码格式
request.setCharacterEncoding(”UTF-8”);
Date date = new Date();//获取当前时间
SimpleDateFormat sdfFileName = new SimpleDateFormat(“yyyyMMddHHmmss”);
SimpleDateFormat sdfFolder = new SimpleDateFormat(“yyMM”);
String newfileName = sdfFileName.format(date);//文件名称
String fileRealPath = ”“;//文件存放真实地址

String fileRealResistPath = ”“;//文件存放真实相对路径

//名称 界面编码 必须 和request 保存一致..否则乱码
String name = request.getParameter(”name”);

String firstFileName=”“;
// 获得容器中上传文件夹所在的物理路径
String savePath = this.getServletConfig().getServletContext().getRealPath(“/”) + “uploads\\” + newfileName +”\\”;
System.out.println(”路径” + savePath+“; name:”+name);
File file = new File(savePath);
if (!file.isDirectory()) {
file.mkdirs();
}

try {
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding(”UTF-8”);
// 获取多个上传文件
List fileList = fileList = upload.parseRequest(request);
// 遍历上传文件写入磁盘
Iterator it = fileList.iterator();
while (it.hasNext()) {
Object obit = it.next();
if(obit instanceof DiskFileItem){
System.out.println(”xxxxxxxxxxxxx”);
DiskFileItem item = (DiskFileItem) obit;

// 如果item是文件上传表单域
// 获得文件名及路径
String fileName = item.getName();
if (fileName != null) {
firstFileName=item.getName().substring(item.getName().lastIndexOf(”\\”)+1);
String formatName = firstFileName.substring(firstFileName.lastIndexOf(”.”));//获取文件后缀名
fileRealPath = savePath + newfileName+ formatName;//文件存放真实地址

BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出流
Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹
//上传成功,则插入数据库
if (new File(fileRealPath).exists()) {
//虚拟路径赋值
fileRealResistPath=sdfFolder.format(date)+”/”+fileRealPath.substring(fileRealPath.lastIndexOf(“\\”)+1);
//保存到数据库
System.out.println(”保存到数据库:”);
System.out.println(”name:”+name);
System.out.println(”虚拟路径:”+fileRealResistPath);
}

}
}
}
} catch (org.apache.commons.fileupload.FileUploadException ex) {
ex.printStackTrace();
System.out.println(”没有上传文件”);
return;
}
response.getWriter().write(”1”);

}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}


package com.rh.core.upload;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
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.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

public class Uploadify extends HttpServlet{
private static final long serialVersionUID = 1L;

/**
* 实现多文件的同时上传
*/
public void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {

//设置接收的编码格式
request.setCharacterEncoding("UTF-8");
Date date = new Date();//获取当前时间
SimpleDateFormat sdfFileName = new SimpleDateFormat("yyyyMMddHHmmss");
SimpleDateFormat sdfFolder = new SimpleDateFormat("yyMM");
String newfileName = sdfFileName.format(date);//文件名称
String fileRealPath = "";//文件存放真实地址

String fileRealResistPath = "";//文件存放真实相对路径

//名称  界面编码 必须 和request 保存一致..否则乱码
String name = request.getParameter("name");

String firstFileName="";
// 获得容器中上传文件夹所在的物理路径
String savePath = this.getServletConfig().getServletContext().getRealPath("/") + "uploads\\" + newfileName +"\\";
System.out.println("路径" + savePath+"; name:"+name);
File file = new File(savePath);
if (!file.isDirectory()) {
file.mkdirs();
}

try {
DiskFileItemFactory fac = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(fac);
upload.setHeaderEncoding("UTF-8");
// 获取多个上传文件
List fileList = fileList = upload.parseRequest(request);
// 遍历上传文件写入磁盘
Iterator it = fileList.iterator();
while (it.hasNext()) {
Object obit = it.next();
if(obit instanceof DiskFileItem){
System.out.println("xxxxxxxxxxxxx");
DiskFileItem item = (DiskFileItem) obit;

// 如果item是文件上传表单域
// 获得文件名及路径
String fileName = item.getName();
if (fileName != null) {
firstFileName=item.getName().substring(item.getName().lastIndexOf("\\")+1);
String formatName = firstFileName.substring(firstFileName.lastIndexOf("."));//获取文件后缀名
fileRealPath = savePath + newfileName+ formatName;//文件存放真实地址

BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(new File(fileRealPath)));// 获得文件输出流
Streams.copy(in, outStream, true);// 开始把文件写到你指定的上传文件夹
//上传成功,则插入数据库
if (new File(fileRealPath).exists()) {
//虚拟路径赋值
fileRealResistPath=sdfFolder.format(date)+"/"+fileRealPath.substring(fileRealPath.lastIndexOf("\\")+1);
//保存到数据库
System.out.println("保存到数据库:");
System.out.println("name:"+name);
System.out.println("虚拟路径:"+fileRealResistPath);
}

}
}
}
} catch (org.apache.commons.fileupload.FileUploadException ex) {
ex.printStackTrace();
System.out.println("没有上传文件");
return;
}
response.getWriter().write("1");

}

public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}


web.xml

[html] view plain copy print?<?xml version=“1.0” encoding=“UTF-8”?>
<web-app id=“WebApp_ID” 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>Uploadify</servlet-name>
<servlet-class>com.rh.core.upload.Uploadify</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Uploadify</servlet-name>
<url-pattern>/scripts/uploadify</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" 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>Uploadify</servlet-name>
<servlet-class>com.rh.core.upload.Uploadify</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Uploadify</servlet-name>
<url-pattern>/scripts/uploadify</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>


项目截图:(可能需要修改css文件中图片的位置)

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  jquery