上传文件jquery,上传文件 百度网盘

使用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)]

更多用法可以 参考官网

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

tdinput 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-form的FormData上传文件带参数

html示例内容如下:

直接使用FormData提交文件的话,不带参数可以用下面的方法:

FormData的数据会自动组织成multipart/form-data形式的,因此不需要JQuery进行转化了,因此contentType,processData为false。

但是上面这种方法不适合带参数的,如果上传还要求带上参数的话,可以使用如下方法:

这种方法带上参数了,而文件的参数名为input type="file" name="file"中定义的name名,要修改参数名只需要在这里name名。

jQuery实现文件上传。

/* jQuery实现文件上传,参考例子如下:

package com.kinth.hddpt.file.action;  

import java.io.File;  

import java.io.FileNotFoundException;  

import java.io.FileOutputStream;  

import java.io.IOException;  

import java.io.InputStream;  

import java.io.OutputStream;  

import java.util.ArrayList;  

import java.util.Calendar;  

import java.util.Enumeration;  

import java.util.Hashtable;  

import java.util.List;  

import javax.servlet.http.HttpServletRequest;  

import javax.servlet.http.HttpServletResponse;  

import net.sf.json.JSONArray;  

import org.apache.commons.logging.Log;  

import org.apache.commons.logging.LogFactory;  

import org.apache.struts.action.ActionForm;  

import org.apache.struts.action.ActionForward;  

import org.apache.struts.action.ActionMapping;  

import org.apache.struts.upload.FormFile;  

import org.hibernate.criterion.MatchMode;  

import org.hibernate.criterion.Order;  

import org.hibernate.criterion.Restrictions;  

import com.gdcn.bpaf.common.base.search.MyCriteria;  

import com.gdcn.bpaf.common.base.search.MyCriteriaFactory;  

import com.gdcn.bpaf.common.base.service.BaseService;  

import com.gdcn.bpaf.common.helper.PagerList;  

import com.gdcn.bpaf.common.helper.WebHelper;  

import com.gdcn.bpaf.common.taglib.SplitPage;  

import com.gdcn.bpaf.security.model.LogonVO;  

import com.gdcn.components.appauth.common.helper.DictionaryHelper;  

import com.kinth.common.base.action.BaseAction;  

import com.kinth.hddpt.file.action.form.FileCatalogForm;  

import com.kinth.hddpt.file.model.FileCatalog;  

import com.kinth.hddpt.file.service.FileCatalogService;  

import com.kinth.hddpt.file.util.MyZTreeNode;  

/** 

* p 

* description: “文件上传的Struts层请求处理类” 

* /p 

* @date : 2013-1-14 

*/  

public class FileCatalogAction extends BaseActionFileCatalog {  

@SuppressWarnings("unused")  

private static Log log = LogFactory.getLog(FileCatalogAction.class); // 日志记录  

private FileCatalogService fileCatalogService;  

// 删除记录的同时删除相应文件  

public ActionForward fileDelete(ActionMapping mapping, ActionForm form,  

HttpServletRequest request, HttpServletResponse response)  

throws Exception {  

String[] id = request.getParameterValues("resourceId");  

if (id != null  id[0].contains(",")) {  

id = id[0].split(",");  

}  

String[] fileUrls = new String[id.length];  

for (int j = 0; j  id.length; j++) {  

fileUrls[j] = fileCatalogService.findObject(id[j]).getFileUrl();  

if (!isEmpty(fileUrls[j])) {  

// 如果该文件夹不存在则创建一个uptext文件夹  

File fileup = new File(fileUrls[j]);  

if (fileup.exists() || fileup != null) {  

fileup.delete();  

}  

}  

fileCatalogService.deleteObject(id[j]);  

}  

setAllActionInfos(request);  

return list(mapping, form, request, response);  

}  

@Override  

public ActionForward save(ActionMapping mapping, ActionForm form,  

HttpServletRequest request, HttpServletResponse response)  

throws Exception {  

String id = request.getParameter("resourceId");   

Boolean fileFlag = Boolean.valueOf(request.getParameter("fileFlag"));  

if(fileFlag != null  fileFlag == true){  

return super.save(mapping, form, request, response);  

}else{  

String fileUrl = 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();  

}  

return null;  

}  

@SuppressWarnings("unchecked")  

public String fileUpload(ActionForm form,HttpServletRequest request,String id,Boolean fileFlag) throws FileNotFoundException, IOException{  

request.setCharacterEncoding("GBK");  

String basePath = getServlet().getServletConfig().getServletContext().getRealPath("")+"/";  

String filePath = "uploads/"; // 获取项目根路径    ;  

/*注释部分对应jquery upload uploadify插件的后台代码,只是还存在编码问题,默认为utf-8 

String savePath = getServlet().getServletConfig().getServletContext().getRealPath(""); // 获取项目根路径 

savePath = savePath + "\\uploads\\"; 

//读取上传来的文件信息 

HashtableString, FormFile fileHashtable = form.getMultipartRequestHandler().getFileElements(); 

EnumerationString enumeration = fileHashtable.keys(); 

enumeration.hasMoreElements(); 

String key = (String) enumeration.nextElement(); 

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

String filename = formFile.getFileName().trim(); //文件名 

filename = new EncodeChange().changeCode(filename); 

String filetype = filename.substring(filename.lastIndexOf(".") + 1);//文件类型 

savePath = savePath+filetype+"\\"; 

System.out.println("path:"+savePath); 

String realPath = savePath +  filename; //真实文件路径 

//如果该文件夹不存在则创建一个文件夹 

File fileup = new File(savePath); 

if(!fileup.exists()||fileup==null){ 

fileup.mkdirs(); 

if (!filename.equals("")) { 

// 在这里上传文件 

InputStream is = formFile.getInputStream(); 

OutputStream os = new FileOutputStream(realPath); 

int bytesRead = 0; 

byte[] buffer = new byte[8192]; 

while ((bytesRead = is.read(buffer, 0, 8192)) != -1) { 

os.write(buffer, 0, bytesRead); 

os.close(); 

is.close(); 

//如果是修改操作,则删除原来的文件 

String id = request.getParameter("resourceId"); 

if (!isEmpty(id)) { 

FileCatalog fileCatalog = fileCatalogService.findObject(id); 

String fileUrl = fileCatalog.getFileUrl(); 

if (!isEmpty(fileUrl)) { 

File filedel = new File(fileUrl); 

if(filedel.exists()||filedel!=null){ 

filedel.delete(); 

request.setAttribute("entity", fileCatalog); 

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

}*/  

// 读取上传来的文件信息  

HashtableString, FormFile fileHashtable = form.getMultipartRequestHandler().getFileElements();  

EnumerationString enumeration = fileHashtable.keys();  

enumeration.hasMoreElements();  

String key = (String) enumeration.nextElement();  

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

String filename = formFile.getFileName().trim(); // 文件名  

String filetype = filename.substring(filename.lastIndexOf(".") + 1);// 文件类型       

Integer fileSize = formFile.getFileSize();  

filePath += Calendar.getInstance().get(Calendar.YEAR)+"/"+filetype+"/" ;  

String realPath = basePath+filePath+filename;  // 真实文件路径  

if (!filename.equals("")) {  

// 如果是修改操作,则删除原来的文件  

if (!isEmpty(id)) {  

FileCatalog fileCatalog = fileCatalogService.findObject(id);  

String fileUrl = fileCatalog.getFileUrl();  

if (!isEmpty(fileUrl)) {  

fileUrl = basePath + fileUrl;  

File filedel = new File(fileUrl);  

if (filedel.exists() || filedel != null) {  

filedel.delete();  

}  

}  

request.setAttribute("entity", fileCatalog);  

}  

// 如果该文件夹不存在则创建一个文件夹  

File fileup = new File(basePath+filePath);  

if (!fileup.exists() || fileup == null) {  

fileup.mkdirs();  

}  

// 在这里上传文件  

InputStream is = formFile.getInputStream();  

OutputStream os = new FileOutputStream(realPath);  

int bytesRead = 0;  

byte[] buffer = new byte[8192];  

while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {  

os.write(buffer, 0, bytesRead);  

}  

os.close();  

is.close();  

}  

filePath += filename;  

String result = "{\"fileName\":\""+filename+"\",\"fileType\":\""+filetype+"\",\"fileSize\":"+fileSize+",\"fileUrl\":\""+filePath+"\"}";           

return result;  

}  

public FileCatalogService getFileCatalogService() {  

return fileCatalogService;  

}  

public void setFileCatalogService(FileCatalogService fileCatalogService) {  

this.fileCatalogService = fileCatalogService;  

}  

}

使用jquery上传文件

核心原理

1、点击按钮后讲file存为变量,创建FromData对象,讲file追加到fd里面;

2、发起ajax请求,将fd传送到指定的接口;

3、当服务器回应数据时,使用attr方法修改图片URL,将图片文件显示到页面中;

3、发起ajaxStart事件,监听到ajax请求发起时,显示loading;

3、发起ajaxStop事件,监听到ajax请求结束时,关闭loading;

HTML

JS

网页名称:上传文件jquery,上传文件 百度网盘
分享地址:https://www.cdcxhl.com/article16/dsgphdg.html

成都网站建设公司_创新互联,为您提供微信小程序搜索引擎优化移动网站建设用户体验云服务器网站设计

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设