当前位置:首页 » 文件管理 » jquery插件文件上传

jquery插件文件上传

发布时间: 2022-11-26 16:42:04

‘壹’ jquery Uploadify上传文件

Uploadify是JQuery的一个上传插件,实现的效果非常不错,带进度显示。不过官方提供的实例时php版本的,本文将详细介绍Uploadify在Aspnet中的使用,您也可以点击下面的链接进行演示或下载。

首先按下面的步骤来实现一个简单的上传功能。

1 创建Web项目,命名为JQueryUploadDemo,从官网上下载最新的版本解压后添加到项目中。

2 在项目中添加UploadHandler.ashx文件用来处理文件的上传。

3 在项目中添加UploadFile文件夹,用来存放上传的文件。

进行完上面三步后项目的基本结构如下图:

‘贰’ jquery上传文件是怎么实现的

本篇文章是对Jquery中的LigerUI实现文件上传的方法,进行了分析介绍,需要的朋友可以参考下
一、在Head中加入
<script src="../lib/js/ajaxfileupload.js" type="text/javascript"></script>
<script src="../lib/js/ligerui.expand.js" type="text/javascript"></script>
二、Html中的Div代码

复制代码 代码如下:
<div id="AppendBill_Div" style="display:none;"> <%-- 上传 - 单 --%>
<table style="height:100%;width:100%">
<tr style="height:40px">
<td style="width:20%">
图标:
</td>
<td><input type="file" style="width:200px" id="fileupload" name="fileupload"/>
</td>
</tr>
</table>
</div>

三、Js中-写的是关键部分,会LigerUI的朋友-你懂得
1、grid中添加项【存地址字段】
{ display: "扫描件", name: "AppendBillPath", width: 120, type: "text", align: "left" }
2、Form可添加项【存地址和弹出选择框】
{ name: "AppendBillPath1", type: "hidden" }, // --上传-【5】--
{ display: "扫描件", name: "AppendBillPath", comboboxName: "AppendBillPath2", newline: true, labelWidth: 100, width: 150, space: 30, type: "select", options: {}} // --上传-【6】--
$.ligerui.get("AppendBillPath2").set('onBeforeOpen', f_selectAppendBillPath_1) // 【扫描件】 // --上传-【7】--
3、事件
// #region ======================================= 【上传扫描件窗口】 // --上传-【8】--
复制代码 代码如下:
var AppendBillPathDetail = null;
function f_selectAppendBillPath_1() {
var imageurl = $("#AppendBill").val();
var AppendBill_Id = $("#AppendBill").val(); // 单号
if (imageurl.length == 0) {
LG.showError("您没有输入单号,请输入随单号!");
return;
}
if (AppendBillPathDetail) {
AppendBillPathDetail.show();
}
else {
AppendBillPathDetail = $.ligerDialog.open({
target: $("#AppendBill_Div"), title: '添加图标',
width: 360, height: 170, top: 170, left: 280, // 弹出窗口大小
buttons: [
{ text: '上传', onclick: function () { AppendBillPath_save(); } },
{ text: '取消', onclick: function () { AppendBillPathDetail.hide(); } }
]
});
}
}
function AppendBillPath_save()
{
var imgurl = $("#fileupload").val();
// var filehelpcode = $("#filehelpcode").val();
var extend = imgurl.substring(imgurl.lastIndexOf("."), imgurl.length);
extend = extend.toLowerCase();
if (extend == ".jpg" || extend == ".jpeg" || extend == ".png" || extend == ".gif" || extend == ".bmp")
{
}
else
{
LG.showError("请上传jpg,jpep,png,gif,bmp格式的图片文件");
return;
}
var imageurl = $("#AppendBill").val(); // extend
alert(imageurl);
$.ajaxFileUpload({
url: "../handle/ImageUpload.aspx?imageurl=" + imageurl, // --上传-【9】-- aspx文件
secureuri: false,
fileElementId: "fileupload", //Input file id
dataType: "text",
success: function (data, status)
{
// ----------------- // 保存路径
// $("#AppendBillPath2").val(Data);

LG.tip(data);
f_reload();
},
error: function (data, status, e) {
LG.showError(data);
}
});
}
// #endregion

四、后台cs,写一句关键的,可以返回参数,前台提示
string url = Server.MapPath("/Image/" + gfilename + filenameext); // 执行上传操作

‘叁’ jquery 上传文件插件uploadify jsp版本

写一个servlet,看这里
http://www.javaeye.com/topic/376101

‘肆’ DWZ中怎样整合JQuery的ajaxFileUpload上传插件

jQuery插件AjaxFileUpload可以实现ajax文件上传,需要jQuery库文件和ajaxfileupload.js
一.引入部分
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>

二.<body>部分

<img src="images/nophoto.jpg" id="picture" width="160px" height="200px"/>
<input type="file" id="touxiang" name="photo" size="10" onchange="changImg()"/>

注意:使用AjaxFileUpload插件上传文件可不需要form

<form name="form" action="" method="POST" enctype="multipart/form-data">

……相关html代码……

</form>

三.js部分

function changImg(){

$.ajaxFileUpload
(
{
url:'XXX.action', //上传文件的服务端
secureuri:false, //是否启用安全提交
dataType: 'text', //数据类型
fileElementId:'touxiang', //表示文件域ID

//提交成功后处理函数 html为返回值,status为执行的状态
success: function(html,status)
{

},

//提交失败处理函数
error: function (html,status,e)
{

}
}
)

}

四.原理

利用jQuery的选择器获得file文件上传框中的文件路径值,然后动态的创建一个iframe,并在里面建立一个新的file 文件框,提供post方式提交到后台。最后,返回结果到前台。

五.总结

使用jQuery插件AjaxFileUpload实现无刷新上传文件非常实用,由于其简单易用,因些这个插件相比其它文件上传插件使用人数最多,非常值得推荐。

‘伍’ 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实现文件上传。

/*jQuery实现文件上传,参考例子如下:
packagecom.kinth.hddpt.file.action;

importjava.io.File;
importjava.io.FileNotFoundException;
importjava.io.FileOutputStream;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.OutputStream;
importjava.util.ArrayList;
importjava.util.Calendar;
importjava.util.Enumeration;
importjava.util.Hashtable;
importjava.util.List;

importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;

importnet.sf.json.JSONArray;

importorg.apache.commons.logging.Log;
importorg.apache.commons.logging.LogFactory;
importorg.apache.struts.action.ActionForm;
importorg.apache.struts.action.ActionForward;
importorg.apache.struts.action.ActionMapping;
importorg.apache.struts.upload.FormFile;
importorg.hibernate.criterion.MatchMode;
importorg.hibernate.criterion.Order;
importorg.hibernate.criterion.Restrictions;

importcom.gdcn.bpaf.common.base.search.MyCriteria;
importcom.gdcn.bpaf.common.base.search.MyCriteriaFactory;
importcom.gdcn.bpaf.common.base.service.BaseService;
importcom.gdcn.bpaf.common.helper.PagerList;
importcom.gdcn.bpaf.common.helper.WebHelper;
importcom.gdcn.bpaf.common.taglib.SplitPage;
importcom.gdcn.bpaf.security.model.LogonVO;
importcom.gdcn.components.appauth.common.helper.DictionaryHelper;
importcom.kinth.common.base.action.BaseAction;
importcom.kinth.hddpt.file.action.form.FileCatalogForm;
importcom.kinth.hddpt.file.model.FileCatalog;
importcom.kinth.hddpt.file.service.FileCatalogService;
importcom.kinth.hddpt.file.util.MyZTreeNode;

/**
*<p>
*description:“文件上传的Struts层请求处理类”
*</p>
*@date:2013-1-14
*/
<FileCatalog>{
@SuppressWarnings("unused")
privatestaticLoglog=LogFactory.getLog(FileCatalogAction.class);//日志记录
;

//删除记录的同时删除相应文件
publicActionForwardfileDelete(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsException{
String[]id=request.getParameterValues("resourceId");

if(id!=null&&id[0].contains(",")){
id=id[0].split(",");
}
String[]fileUrls=newString[id.length];
for(intj=0;j<id.length;j++){
fileUrls[j]=fileCatalogService.findObject(id[j]).getFileUrl();
if(!isEmpty(fileUrls[j])){
//如果该文件夹不存在则创建一个uptext文件夹
Filefileup=newFile(fileUrls[j]);
if(fileup.exists()||fileup!=null){
fileup.delete();
}
}

fileCatalogService.deleteObject(id[j]);
}
setAllActionInfos(request);
returnlist(mapping,form,request,response);
}


@Override
publicActionForwardsave(ActionMappingmapping,ActionFormform,
HttpServletRequestrequest,HttpServletResponseresponse)
throwsException{
Stringid=request.getParameter("resourceId");
BooleanfileFlag=Boolean.valueOf(request.getParameter("fileFlag"));

if(fileFlag!=null&&fileFlag==true){
returnsuper.save(mapping,form,request,response);
}else{
StringfileUrl=this.fileUpload(form,request,id,fileFlag);
response.setContentType("text/html");
response.setCharacterEncoding("GBK");
response.setHeader("Charset","GBK");
response.setHeader("Cache-Control","no-cache");
response.getWriter().write(fileUrl);
response.getWriter().flush();
}
returnnull;
}

@SuppressWarnings("unchecked")
publicStringfileUpload(ActionFormform,HttpServletRequestrequest,Stringid,BooleanfileFlag)throwsFileNotFoundException,IOException{

request.setCharacterEncoding("GBK");

StringbasePath=getServlet().getServletConfig().getServletContext().getRealPath("")+"/";
StringfilePath="uploads/";//获取项目根路径;

/*注释部分对应jqueryuploaploadify插件的后台代码,只是还存在编码问题,默认为utf-8
StringsavePath=getServlet().getServletConfig().getServletContext().getRealPath("");//获取项目根路径
savePath=savePath+"\uploads\";
//读取上传来的文件信息
Hashtable<String,FormFile>fileHashtable=form.getMultipartRequestHandler().getFileElements();
Enumeration<String>enumeration=fileHashtable.keys();
enumeration.hasMoreElements();
Stringkey=(String)enumeration.nextElement();

FormFileformFile=(FormFile)fileHashtable.get(key);

Stringfilename=formFile.getFileName().trim();//文件名
filename=newEncodeChange().changeCode(filename);
Stringfiletype=filename.substring(filename.lastIndexOf(".")+1);//文件类型
savePath=savePath+filetype+"\";
System.out.println("path:"+savePath);
StringrealPath=savePath+filename;//真实文件路径

//如果该文件夹不存在则创建一个文件夹
Filefileup=newFile(savePath);
if(!fileup.exists()||fileup==null){
fileup.mkdirs();
}
if(!filename.equals("")){
//在这里上传文件
InputStreamis=formFile.getInputStream();
OutputStreamos=newFileOutputStream(realPath);
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=is.read(buffer,0,8192))!=-1){
os.write(buffer,0,bytesRead);
}
os.close();
is.close();
//如果是修改操作,则删除原来的文件
Stringid=request.getParameter("resourceId");
if(!isEmpty(id)){
FileCatalogfileCatalog=fileCatalogService.findObject(id);
StringfileUrl=fileCatalog.getFileUrl();
if(!isEmpty(fileUrl)){
Filefiledel=newFile(fileUrl);
if(filedel.exists()||filedel!=null){
filedel.delete();
}
}

request.setAttribute("entity",fileCatalog);
}

response.getWriter().print(realPath);//向页面端返回结果信息
}*/

//读取上传来的文件信息
Hashtable<String,FormFile>fileHashtable=form.getMultipartRequestHandler().getFileElements();
Enumeration<String>enumeration=fileHashtable.keys();
enumeration.hasMoreElements();
Stringkey=(String)enumeration.nextElement();

FormFileformFile=(FormFile)fileHashtable.get(key);

Stringfilename=formFile.getFileName().trim();//文件名
Stringfiletype=filename.substring(filename.lastIndexOf(".")+1);//文件类型
IntegerfileSize=formFile.getFileSize();


filePath+=Calendar.getInstance().get(Calendar.YEAR)+"/"+filetype+"/";
StringrealPath=basePath+filePath+filename;//真实文件路径

if(!filename.equals("")){
//如果是修改操作,则删除原来的文件
if(!isEmpty(id)){
FileCatalogfileCatalog=fileCatalogService.findObject(id);
StringfileUrl=fileCatalog.getFileUrl();
if(!isEmpty(fileUrl)){
fileUrl=basePath+fileUrl;
Filefiledel=newFile(fileUrl);
if(filedel.exists()||filedel!=null){
filedel.delete();
}
}
request.setAttribute("entity",fileCatalog);
}
//如果该文件夹不存在则创建一个文件夹
Filefileup=newFile(basePath+filePath);
if(!fileup.exists()||fileup==null){
fileup.mkdirs();
}
//在这里上传文件
InputStreamis=formFile.getInputStream();
OutputStreamos=newFileOutputStream(realPath);
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=is.read(buffer,0,8192))!=-1){
os.write(buffer,0,bytesRead);
}
os.close();
is.close();
}
filePath+=filename;
Stringresult="{"fileName":""+filename+"","fileType":""+filetype+"","fileSize":"+fileSize+","fileUrl":""+filePath+""}";
returnresult;

}

(){
returnfileCatalogService;
}

(){
this.fileCatalogService=fileCatalogService;
}

}

‘柒’ 如何用 jQuery 直接传文件至七牛

操作方法如下: jquery有个插件叫uplodify,你搜下,可以用它来上传,并有上传进度条等功能!

‘捌’ 使用jquery.form.js实现文件上传及进度条前端代码

ajax的表单提交只能提交data数据到后台,没法实现file文件的上传还有展示进度功能,这里用到form.js的插件来实现,搭配css样式简单易上手,而且高大上,推荐使用。

需要解释下我的结构, #upload-input-file 的input标签是真实的文件上传按钮,包裹form标签后可以实现上传功能, #upload-input-btn 的button标签是展示给用户的按钮,因为需要样式的美化。上传完成生成的文件名将会显示在 .upload-file-result 里面, .progress 是进度条的位置,先让他隐藏加上 hidden 的class, .progress-bar 是进度条的主体, .progress-bar-status 是进度条的文本提醒。

去掉hidden的class,看到的效果是这样的
[图片上传失败...(image-2c700a-1548557865446)]

将上传事件绑定在file的input里面,绑定方式就随意了。
var progress = $(".progress-bar"), status = $(".progress-bar-status"), percentVal = '0%'; //上传步骤 $("#myupload").ajaxSubmit({ url: uploadUrl, type: "POST", dataType: 'json', beforeSend: function () { $(".progress").removeClass("hidden"); progress.width(percentVal); status.html(percentVal); }, uploadProgress: function (event, position, total, percentComplete) { percentVal = percentComplete + '%'; progress.width(percentVal); status.html(percentVal); console.log(percentVal, position, total); }, success: function (result) { percentVal = '100%'; progress.width(percentVal); status.html(percentVal); //获取上传文件信息 uploadFileResult.push(result); // console.log(uploadFileResult); $(".upload-file-result").html(result.name); $("#upload-input-file").val(''); }, error: function (XMLHttpRequest, textStatus, errorThrown) { console.log(errorThrown); $(".upload-file-result").empty(); } });

[图片上传失败...(image-3d6ae0-1548557865446)]

[图片上传失败...(image-9f0adf-1548557865446)]

更多用法可以 参考官网

‘玖’ 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的上传插件ajaxFileUpload上传文件给webservice

var
elementIds=["flag"];
//flag为id、name属性名
$.ajaxFileUpload({
url:
'uploadAjax.htm',
type:
'post',
secureuri:
false,
//一般设置为false
fileElementId:
'file',
//
上传文件的id、name属性名
dataType:
'text',
//返回值类型,一般设置为json、application/json
elementIds:
elementIds,
//传递参数到服务器
success:
function(data,
status){
alert(data);
},
error:
function(data,
status,
e){
alert(e);
}
});

热点内容
c可以用来编译系统软件吗 发布:2024-10-05 16:22:26 浏览:17
U盘和存储器 发布:2024-10-05 16:22:04 浏览:896
cmdc语言 发布:2024-10-05 15:58:32 浏览:550
服务器怎么弄公网ip 发布:2024-10-05 15:57:02 浏览:640
设备配置在什么地方 发布:2024-10-05 15:44:59 浏览:249
matlab外部接口编程 发布:2024-10-05 15:36:58 浏览:365
C事件编程 发布:2024-10-05 15:15:43 浏览:639
一台服务器出现两IP 发布:2024-10-05 15:10:05 浏览:925
md5加密算法c 发布:2024-10-05 15:05:40 浏览:761
如何重设控制器密码 发布:2024-10-05 14:19:13 浏览:441