一、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;
}
}
二、jQuery fileupload 多文件上传
//js
$(function(){
//文件上传地址
//varurl='http://localhost/index.php/upload/do_upload';
varurl='http://localhost/index.php/uploadwe';
//初始化,主要是设置上传参数,以及事件处理方法(回调函数)
$('#fileupload').fileupload({
autoUpload:true,//是否自动上传
//url:url,//上传地址
dataType:'json',
done:function(e,data){//设置文件上传完毕事件的回调函数
//$.each(data.result.files,function(index,file){
$("#myimg").attr({src:data.result.imgurl});
$("#myimg").css({width:"290px",height:"218px"});
//alert(data.result);
},
progressall:function(e,data){//设置上传进度事件的回调函数
varprogress=parseInt(data.loaded/data.total*5,10);
$('#progress.bar').css(
'width',
progress+'%'
);
}
});
});
//上传至服务后,服务器返回json数据--上传图片的地址。
//html
<labelfor="text">上传图片</label>
<inputid="fileupload"type="file"name="files"data-url="<spanstyle="color:#ff6666;">jquery_save_img</span>"multiple>
//data-url为上传至服务器端的处理接口/地址,可替换js中的url
//服务器端
functionjquery_save_img()
{
$arrType=array('image/jpg','image/gif','image/png','image/bmp','image/pjpeg','image/jpeg');
$max_size='500000000000';//最大文件限制(单位:byte)
$upfile='./uploads';//图片目录路径
$file=$_FILES['files'];
/*
echo'filename:'.$file['tmp_name'].';<br/>';
echo'size:'.$file['size'].';<br/>';
echo'type:'.$file['type'].';<br/>';
echo'name:'.$file['name'].';<br/>';
*/
if($_SERVER['REQUEST_METHOD']=='POST'){//判断提交方式是否为POST
if(!is_uploaded_file($file['tmp_name'])){//判断上传文件是否存在
echo"<fontcolor='#FF0000'>文件不存在!</font>";
exit;
}
if($file['size']>$max_size){//判断文件大小是否大于500000字节
echo"<fontcolor='#FF0000'>上传文件太大!</font>";
exit;
}
if(!in_array($file['type'],$arrType)){//判断图片文件的格式
echo"<fontcolor='#FF0000'>上传文件格式不对!</font>xxx:".$file['type'];
exit;
}
if(!file_exists($upfile)){//判断存放文件目录是否存在
mkdir($upfile,0777,true);
}
$imageSize=getimagesize($file['tmp_name']);
$img=$imageSize[0].'*'.$imageSize[1];
$fname=$file['name'];
$ftype=explode('.',$fname);
$picName=$upfile."/cloudy".$fname;
if(file_exists($picName)){
//echo"<fontcolor='#FF0000'>同文件名已存在!</font>";
//exit;
}
if(!move_uploaded_file($file['tmp_name'],$picName)){
echo"<fontcolor='#FF0000'>移动文件出错!</font>";
exit;
}
else{
/*
echo"<fontcolor='#FF0000'>图片文件上传成功!</font><br/>";
echo"<fontcolor='#0000FF'>图片大小:$img</font><br/>";
echo"图片预览:<br><divstyle='border:#F001pxsolid;width:200px;height:200px'>
<imgsrc=\"".$picName."\"width=200pxheight=200px>".$fname."</div>";
*/
echo'{"imgurl":"http://localhost/uploads/cloudy'.$fname.'"}';
}
}
}
三、jQuery-File-Upload怎么清空
jquery异步上传,一般来说这里上传调用的是系统专门上传的action,上传好后返回上传文件信息。你这里result.files就是返回的上传结果。这个需要你在后台自己封装。你前端需要什么,后台就封装什么。
比如我以前写过一个
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Map<String, Object> fileObject= new HashMap<String, Object>();
fileinfo.put("size", size);//原始文件大小
fileObject.put("original", original);//原始文件唯一标识
fileObject.put("originalPath", originalPath);//原始文件临时存储目录
fileObject.put("thumb", thumb);//图片的预览文件唯一标识
fileObject.put("thumbPath", thumbPath);//图片预览文件临时存储目录
fileObject.put("name", fileFileName);//原始图片名称
fileObject.put("url", url);//原始图片的web查看地址,这个可以设置img.src属性
fileObject.put("thumbnailUrl", thumbnailUrl);//预览图片的web查看地址
fileObject.put("contentType", fileContentType);//上传文件type
fileObject.put("deleteType","POST");//这是我自己封装的post删除
//这个是我自己封装的删除路径
fileObject.put("deleteUrl", super.getRequest().getContextPath()+"/removeUpload.do?id="+ original);
Map[] fileArray= new HashMap[1];
fileArray[0]= fileObject;
JSONObject jsonObject= new JSONObject();
jsonObject.put("files", JSONArray.fromObject(fileArray));
HttpServletResponse response= getResponse();
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write(jsonObject.toString());
response.getWriter().flush();
而前断可以将上传文件的唯一标识放到一个隐藏域里,表单提交的时候一起提发送到后台,再根据唯一标识去取上传文件信息或写或**转移。
前断fileuploaddone我是这么用的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
on('fileuploaddone', function(e, data){
//上传结果
$.each(data.result.files, function(index, file){
if(file.url){
var link=$('<a>').attr('target','_blank').prop('href', file.url);
//这个是文件上传后的展示区域,可以在fileuploadadd事件里构建
var$imgdiv=$(data.context.children()[index]);
var$link=$imgdiv.find("canvas").wrap(link);
$imgdiv.append($('<input type="hidden" name="imagefileid"/>').prop('value', file.original));
$imgdiv.append($('<input type="hidden" name="imagefilename"/>').prop('value', file.name));
} else if(file.error){
var error=$('<span class="text-danger"/>').text(file.error);
$(data.context.children()[index]).append(error);
}
});
})
文章到此结束,如果本次分享的jquery fileupload和jQuery fileupload 多文件上传的问题解决了您的问题,那么我们由衷的感到高兴!