ajaxfileupload带参数上传?jsp中使用jquery的ajaxfileupload插件怎么实现异步上传
一、如何用Ajax实现多文件上传
jquery实现多个上传文件教程:
首先创建解决方案,添加jquery的js和一些资源文件(如图片和进度条显示等):
1
2
3
4
5
jquery-1.3.2.min.js
jquery.uploadify.v2.1.0.js
jquery.uploadify.v2.1.0.min.js
swfobject.js
uploadify.css
1、页面的基本代码如下
这里用的是aspx页面(html也是也可的)
页面中引入的js和js函数如下:
1
2
3
4
5
6
7
<script src="js/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.v2.1.0.js" type="text/javascript"></script>
<script src="js/jquery.uploadify.v2.1.0.min.js" type="text/javascript"></script>
<script src="js/swfobject.js" type="text/javascript"></script>
<link href="css/uploadify.css" rel="stylesheet" type="text/css"/>
</script>
js函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<script type="text/javascript">
$(document).ready(function(){
$("#uploadify").uploadify({
'uploader':'image/uploadify.swf',//uploadify.swf文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后淡出打开文件对话框
'script':'Handler1.ashx',// script:后台处理程序的相对路径
'cancelImg':'image/cancel.png',
'buttenText':'请选择文件',//浏览按钮的文本,默认值:BROWSE。
'sizeLimit':999999999,//文件大小显示
'floder':'Uploader',//上传文件存放的目录
'queueID':'fileQueue',//文件队列的ID,该ID与存放文件队列的div的ID一致
'queueSizeLimit': 120,//上传文件个数限制
'progressData':'speed',//上传速度显示
'auto': false,//是否自动上传
'multi': true,//是否多文件上传
//'onSelect': function(e, queueId, fileObj){
// alert("唯一标识:"+ queueId+"\r\n"+
//"文件名:"+ fileObj.name+"\r\n"+
//"文件大小:"+ fileObj.size+"\r\n"+
//"创建时间:"+ fileObj.creationDate+"\r\n"+
//"最后修改时间:"+ fileObj.modificationDate+"\r\n"+
//"文件类型:"+ fileObj.type);
//}
'onQueueComplete': function(queueData){
alert("文件上传成功!");
return;
}
});
});
页面中的控件代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
<body>
<form id="form1" runat="server">
<div id="fileQueue">
</div>
<div>
<p>
<input type="file" name="uploadify" id="uploadify"/>
<input id="Button1" type="button" value="上传" onclick="javascript:$('#uploadify').uploadifyUpload()"/>
<input id="Button2" type="button" value="取消" onclick="javascript:$('#uploadify').uploadifyClearQueue()"/>
</p>
</div>
</form>
</body>
函数主要参数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
$(document).ready(function(){
$('#fileInput1').fileUpload({
'uploader':'uploader.swf',//不多讲了
'script':'/AjaxByJQuery/file.do',//处理Action
'cancelImg':'cancel.png',
'folder':'',//服务端默认保存路径
'scriptData':{'methed':'uploadFile','arg1','value1'},
//向后台传递参数,methed,arg1为参数名,uploadFile,value1为对应的参数值,服务端通过request["arg1"]
'buttonText':'UpLoadFile',//按钮显示文字,不支持中文,解决方案见下
//'buttonImg':'图片路径',//通过设置背景图片解决中文问题,就是把背景图做成按钮的样子
'multi':'true',//多文件上传开关
'fileExt':'*.xls;*.csv',//文件过滤器
'fileDesc':'.xls',//文件过滤器详解见文档
'onComplete': function(event,queueID,file,serverData,data){
//serverData为服务器端返回的字符串值
alert(serverData);
}
});
});
后台一般处理文件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Net;
using System.Web;
using System.Web.Services;
namespace fupload
{
///<summary>
/// Handler1的摘要说明
///</summary>
public class Handler1: IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType="text/plain";
HttpPostedFile file= context.Request.Files["Filedata"];//对客户端文件的访问
string uploadPath= HttpContext.Current.Server.MapPath(@context.Request["folder"])+"\\";//服务器端文件保存路径
if(file!= null)
{
if(!Directory.Exists(uploadPath))
{
Directory.CreateDirectory(uploadPath);//创建服务端文件夹
}
file.SaveAs(uploadPath+ file.FileName);//保存文件
context.Response.Write("上传成功");
}
else
{
context.Response.Write("0");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
以上方式基本可以实现多文件的上传,大文件大小是在控制在10M以下/。
二、jsp中使用jquery的ajaxfileupload插件怎么实现异步上传
ajaxfileupload实现异步上传的完整例子:
JSP页面中引入的script代码:
<script>
function ajaxFileUpload()
{
$("#loading").ajaxStart(function(){
$(this).show();
})//开始上传文件时显示一个图片
.ajaxComplete(function(){
$(this).hide();
});//文件上传完成将图片隐藏起来
$.ajaxFileUpload({
url:'AjaxImageUploadAction.action',//用于文件上传的服务器端请求地址
secureuri:false,//一般设置为false
fileElementId:'imgfile',//文件上传空间的id属性<input type="file" id="imgfile" name="file"/>
dataType:'json',//返回值类型一般设置为json
success: function(data, status)//服务器成功响应处理函数
{
alert(data.message);//从服务器返回的json中取出message中的数据,其中message为在struts2中定义的成员变量
if(typeof(data.error)!='undefined')
{
if(data.error!='')
{
alert(data.error);
}else
{
alert(data.message);
}
}
},
error: function(data, status, e)//服务器响应失败处理函数
{
alert(e);
}
}
)
return false;
}
</script>
struts.xml配置文件中的配置方法:
<struts>
<package name="struts2" extends="json-default">
<action name="AjaxImageUploadAction" class="com.test.action.ImageUploadAction">
<result type="json" name="success">
<param name="contentType">text/html</param>
</result>
<result type="json" name="error">
<param name="contentType">text/html</param>
</result>
</action>
</package>
</struts>
上传处理的Action ImageUploadAction.action
package com.test.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Arrays;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionSupport;
@SuppressWarnings("serial")
public class ImageUploadAction extends ActionSupport{
private File imgfile;
private String imgfileFileName;
private String imgfileFileContentType;
private String message="你已成功上传文件";
public File getImgfile(){
return imgfile;
}
public void setImgfile(File imgfile){
this.imgfile= imgfile;
}
public String getImgfileFileName(){
return imgfileFileName;
}
public void setImgfileFileName(String imgfileFileName){
this.imgfileFileName= imgfileFileName;
}
public String getImgfileFileContentType(){
return imgfileFileContentType;
}
public void setImgfileFileContentType(String imgfileFileContentType){
this.imgfileFileContentType= imgfileFileContentType;
}
public String getMessage(){
return message;
}
public void setMessage(String message){
this.message= message;
}
@SuppressWarnings("deprecation")
public String execute() throws Exception{
String path= ServletActionContext.getRequest().getRealPath("/upload/mri_img_upload");
String[] imgTypes= new String[]{"gif","jpg","jpeg","png","bmp"};
try{
File f= this.getImgfile();
String fileExt= this.getImgfileFileName().substring(this.getImgfileFileName().lastIndexOf(".")+ 1).toLowerCase();
/*
if(this.getImgfileFileName().endsWith(".exe")){
message="上传的文件格式不允许!!!";
return ERROR;
}*/
/**
*检测上传文件的扩展名是否合法
**/
if(!Arrays.<String> asList(imgTypes).contains(fileExt)){
message="只能上传 gif,jpg,jpeg,png,bmp等格式的文件!";
return ERROR;
}
FileInputStream inputStream= new FileInputStream(f);
FileOutputStream outputStream= new FileOutputStream(path+"/"+ this.getImgfileFileName());
byte[] buf= new byte[1024];
int length= 0;
while((length= inputStream.read(buf))!=-1){
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
} catch(Exception e){
e.printStackTrace();
message="文件上传失败了!!!!";
}
return SUCCESS;
}
}
三、ajaxFileUpload异步上传图片,服务器文件叫多,如何删除啊~~
不太苟同楼上的做法,这种不光耗费服务器资源,也耗费数据库的资源。如果是类似腾讯这种人气的网站。就知道问题了。
说下我在实际中的做法吧。当然我的客户人气没有那么高。每年顶多几万人。
比如有个图像上传预览。也是要及时预览并上传到服务器端。我用的是uploady上传插件。
第一张图片上传后以用户名命名.JPG保存。第二次上传就判断当前用户的photo【这是上传图片保存在数据库中】是否存在,如果存在就以用户名#TEMP#.JPG【如果当前用户的photo已是#TEMP#.JPG结尾则以用户名.JPG】保存。如果不存在就依然以用户名.JPG保存。如此互斥。这样只要你不覆盖用户点击保存前你的那张图片,数据库也不会有变动。预览的图片也就永远只有一张。如果你要清理这1万张预览图那也是相当容易的【比如你可以将预览图放在一个临时文件夹中,做个定时任务,一个星期清理一次也差不多了,顶多也就上万张,平时估计几百张就不错了,而实际用户的图片也是以年份/省市/等单独存放,避免一个文件夹过大】。本人项目中的用法,如有问题,请赐教。