1.准备材料:下载jquery.uploadify上传js
 
注意:这个上传在firefox下会出现问题如果你在项目中加了拦截器,因为session会丢失,所以你可以传参的时候带上你所需要的条件,在拦截器可以不作处理这个上传的servlet,也就是判断url,跳过这个servlet的拦截,或者用其他的方法进行判定,比如根据传过来的参数判断是不是有该用户什么的,这就看自己怎么处理,
   一定要out.print(data);否则会认为上传不成功,因为前台收不到返回值,这个data可以返回你所需要的参数,然后jsp页面进行处理
           'method' : 'GET',
            'scriptData' : {'userid':'<%=userID%>'},//传参的时候网上说method要是get,这个我没有测试,用的时候自己调试一下,我这边已经成功了,需要源代码项目的可以留言+邮箱
    有些参数可以看官网上的API文档
2、jsp代码
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>
<%@ include file="/commons/taglibs.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
String rootpath = request.getContextPath();
long userID = (Long)request.getSession().getAttribute("userID");
//上传url
String sessionId = request.getSession().getId();
StringBuffer uploadUrl = new StringBuffer("http://");
uploadUrl.append(request.getHeader("Host"));
uploadUrl.append(request.getContextPath());
uploadUrl.append("/servlet/UploadSwfTmpPic?sessionId="+sessionId);
//上传url--END
%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>上传</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0"> <!-- 样式及js加载 这儿得注意引入的路径是否正确应用的时候自己多加小心--> <link href="./style/uploadify/default.css" rel="stylesheet" type="text/css" />
<link href="./style/uploadify/uploadify.css" rel="stylesheet" type="text/css" />
<script language="javascript" src="<c:url value="/scripts/jquery.js"/>"></script>
<script type="text/javascript" src="./js/uploadify/swfobject.js"></script>
<script type="text/javascript" src="./js/uploadify/jquery.uploadify.v2.0.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function() { $("#showPic").hide();
$("#uploadify").uploadify({
'uploader' : './js/uploadify/uploadify.swf',
'script' : '<%=uploadUrl.toString()%>',//后台处理的请求
'cancelImg' : './images/cancel.png', //每个文件后面的取消按钮
'folder' : 'uploads',//您想将文件保存到的路径
'queueID' : 'fileQueue',//与下面的id对应
'queueSizeLimit' : 50,
'fileDesc' : '文件格式(*.png;*.jpg;*.gif)',
'fileExt' : '*.png;*.jpg;*.gif', //控制可上传文件的扩展名,启用本项时需同时声明fileDesc
'auto' : true, //是否自动提交
'multi' : false, //是否允许上传多个文件
'simUploadLimit' : 1, //允许同时上传的个数为1
'rollover' : false,//鼠标移到浏览按钮的反应
'method' : 'GET',
'scriptData' : {'userid':'<%=userID%>'},
'buttonText' : 'BROWSE',//BROWSE
'buttonImg' : './js/uploadify/uploadify.jpg',
'hideButton' : true,
'wmode' : 'transparent',
'onComplete': function(event, queueID, fileObj,response,data) {
//后台servlet一定要有返回值,否则会认为不成功,上传进度条也会不消失
if(response != -1){
$("#showPic").show();
var res = response.split("^");
path_pic = res[0];
height_y = res[1];
width_y = res[2];
$('#oimgW').html(width_y);
$('#oimgH').html(height_y);
urlallpic = "<%=rootpath%>/uploadfile/tmpdir/"+path_pic;
}else{
alertWbox($(this), "错误提示", "头像上传失败。", 200, null, 238);
}
},
'onSelect': function(e, queueId, fileObj)
{
//fileQueue
document.getElementById("fileQueue").style.display="";
},
'onError' : function(event, queueID, fileObj)
{
// alert("文件:" + fileObj.name + " 上传失败");
alertWbox($(this), "错误提示", "头像上传失败。", 200, null, 238);
} , 'onAllComplete' : function(event, queueID, fileObj,response,data) {
//所有上传成功的返回返回处理
if(urlallpic != "" ){
document.getElementById("fileQueue").style.display="none";
document.getElementById("showPic").style.display="";
document.getElementById("ferret").src = urlallpic;
document.getElementById("minImg").src = urlallpic;//
// setTimeout("readyPic();",5000);
imgReady(urlallpic, function () {
initcutpic();
});
}
}
})
}); </script>
</head>
<body>
<div id="uploadJqFy">
<div id="fileQueue" style="display:none;"></div>
<input type="file" name="uploadify" id="uploadify" />
<p>仅支持jpg、png、gif格式的图片</p>
</div> </body>
</html>

3.web.xml

<servlet>
<servlet-name>uploadCutpic</servlet-name>
<servlet-class>com.ccsuntel.linkupuser.servlet.user.UploadTmpPhotoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>uploadCutpic</servlet-name>
<url-pattern>/servlet/UploadSwfTmpPic</url-pattern>
</servlet-mapping>

4.servlet代码

package com.ccsuntel.linkupuser.servlet.user;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import javax.imageio.ImageIO;
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; import com.ccsuntel.linkupuser.base.Config;
import com.ccsuntel.linkupuser.base.Constant;
import com.ccsuntel.linkupuser.base.dispatch.Base;
import com.ccsuntel.linkupuser.util.Tool;
import com.ccsuntel.linkupuser.util.UploadTool; public class UploadTmpPhotoServlet extends HttpServlet { @Override
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { } @Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
// 设置内存缓冲区,超过后写入临时文件 factory.setSizeThreshold(10240000);
// 设置临时文件存储位置 String base = Config.getInstance().getWorkGtmpPath();//this.getServletContext().getRealPath("/")+"files"; File file = new File(base);
if(!file.exists())
file.mkdirs();
factory.setRepository(file);
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置单个文件的最大上传值 upload.setFileSizeMax(10002400000l);
// 设置整个request的最大值 upload.setSizeMax(10002400000l);
upload.setHeaderEncoding("UTF-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
PrintWriter out = response.getWriter();
try {
List<?> items = upload.parseRequest(request);
FileItem item = null;
String tpmFilePathName = null;
String savePath = Config.getInstance().getLinkfilesavePath();
Map<String,String> fileNames = new HashMap<String, String>();
for (int i = 0 ;i < items.size(); i++){
item = (FileItem) items.get(i);
// 保存文件 if (!item.isFormField() && item.getName().length() > 0) {
fileNames.put("oldName", item.getName());
String suffixName = item.getName().substring(item.getName().lastIndexOf("."));
String newName=UploadTool.createPhotoID()+suffixName;
fileNames.put("newName", newName);
fileNames.put("fileSize", UploadTool.FormetFileSize(item.getSize()));
//System.out.println(item.getName()+"=="+UploadTool.createPhotoID()+suffixName+"=="+UploadTool.FormetFileSize(item.getSize())+"savePath"+savePath); tpmFilePathName = base + newName;//File.separator item.write(new File(tpmFilePathName));
//UploadTool.removeFile(tpmFilePathName); BufferedImage bufImg = ImageIO.read(new File(tpmFilePathName));
//System.out.print("======"+bufImg.getHeight()+"====="+bufImg.getWidth());
//数据库操作,包图片的路径及其相应的信息保存到数据库,
out.print(newName+"^"+bufImg.getHeight()+"^"+bufImg.getWidth());
}
} //Map<String,String> fileNames = UploadTool.WorkGroupFileUpload(request, Config.getInstance().getLinkfiletmpPath(), Config.getInstance().getLinkfilesavePath()); } catch (FileUploadException e) {
out.print(-1);
e.printStackTrace();
} catch (Exception e) {
out.print(-1);
e.printStackTrace();
}finally{
out.flush();
out.close();
} } }

jquery的uploadify上传jsp+servlet的更多相关文章

  1. 使用jquery插件uploadify上传文件的方法与疑问

    我是学生一枚,专业也不是计算机,但又要用到很多相关技术,所以在技术基础不牢靠的情况下,硬着头皮在做.最近在做一个小项目需要上传图片,而且是需要用ajax的方式.但是利用jquery的ajax方法总会有 ...

  2. SpringMVC+jquery.uploadify 上传文件

    前言 以前用Asp.net MVC+uploadify上传文件,最近学习SpringMVC,所以就用SpringMVC+uploadify做个上传文件的demo. 刚开始用form表单的方式提交,在C ...

  3. MVC3+jquery Uploadify 上传文件

    最近做项目用到了上传图片的功能,以前也写过这类代码,不过都是用传统的file标签,今天整理一个好用的插件Uploadify..都做了一些注释,一看便知. 可以去官网下载最新的:Uploadify下载地 ...

  4. [Plugin] JQuery.uploadify上传文件插件的使用详解For ASP.NET

    URL:http://www.cnblogs.com/xiaopin/archive/2010/01/21/1653523.html 今天下午整理文件上传的例子,感觉收集到的例子都很不人性话,后来找到 ...

  5. CI框架如何在主目录application目录之外使用uploadify上传插件和bootstrap前端框架:

    19:29 2016/3/10CI框架如何在主目录application目录之外使用uploadify上传插件和bootstrap前端框架:项目主路径:F:\wamp\www\graduationPr ...

  6. jQuery.uploadify-----文件上传带进度条,支持多文件上传的插件

    借鉴别人总结的uploadify:基于jquery的文件上传插件,支持ajax无刷新上传,多个文件同时上传,上传进行进度显示,控制文件上传大小,删除已上传文件. uploadify有两个版本,一个用f ...

  7. Uploadify 上传文件插件详解

    Uploadify 上传文件插件详解 Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示.不过官方提供的实例时php版本的,本文将详细介绍Uploadify在Aspnet中 ...

  8. Uploadify上传Excel到数据库

    前两章简单的介绍了Uploadify上传插件的基本使用和相关的属性说明.这一章结合Uploadify+ssh框架+jquery实现Excel上传并保存到数据库.         以前写的这篇文章 Jq ...

  9. uploadify上传控件使用

    uploadify是JQuery的一个上传插件,实现的效果非常不错,并且带进度显示,我将给大家演示如何使用uploadify进行图片上传, 1.点我下载http://www.uploadify.com ...

随机推荐

  1. Win7下部署 .NET MVC网站 之 HTTP错误 403.14-Forbidden 解决方法

    今天在 IIS 7 发布MVC 站点时 遇到 ”HTTP错误 403.14-Forbidden Web 服务器被配置为不列出此目录的内容 “ 的错误提示. 一番折腾后发现在web.config 中加入 ...

  2. C#编码标准--编码习惯

    C#编码标准--编码习惯 0.  书写程序时的大小写规则: a) 类:PascalCase表示法.如 MyClass b) 枚举值:PascalCase表示法.如 Colors.Red c) 枚举类型 ...

  3. JQuery实现隔行变色和突出显示当前行 效果

    运行效果如下图: jquery关键代码: <script type="text/javascript"> //该文件为:js.js // 当鼠标移到表格上是,当前一行背 ...

  4. 安卓网络请求之——OkHttp学习

    之前做安卓项目的时候,HTTP请求用的是android api中的HttpURLConnection和HttpClient,编码比较繁琐,自己封装的也不好.后来知道有很多网络请求的第三方框架,可以方便 ...

  5. PrepareCommand

    /// <summary> /// 执行参数查询 /// </summary> /// <param name="cmd">数据库执行命令< ...

  6. Cisco Anyconnect Secure Mobility Client

    Backup 进入安装文件目录cd anyconnect-3.1.00495/binary 安装sudo./vpnsetup.sh 查看安装情况ps aux  |  grep  cisco 在搜索中, ...

  7. LeetCode_Trapping Rain Water

    Given n non-negative integers representing an elevation map where the width of each bar is 1, comput ...

  8. Ruby中的Symbol与字符串

    刚开始学Ruby,一下子搞不清其中的Symbol(变量需要加:)和字符串有什么区别,为这么要为语言设计这么一个东西.让我很迷惑. 首先,字符串对象,是不同的.比如"String" ...

  9. redis maxmemory设置

    关于maxmemory的设置,如果redis的应用场景是作为db使用,那不要设置这个选项,因为db是不能容忍丢失数据的. 如果作为cache使用,则可以启用这个选项(其实既然有淘汰策略,那就是cach ...

  10. jquery ajax提交json格式的数据,后台接收并显示各个属性

    我的表单如下: <form onsubmit="return false"> <ul> <li><span>用户名</span ...