文件上传显示进度条java版

合集下载

Java 制作进度条

Java  制作进度条

Java 制作进度条
进度条(JProgressBar)是一种以可视化形式显示某些任务进度的组件。

该类实现了一个用于为长时间的操作提供可视化的指示器的GUI进度条。

在任务的完成进度中,进度条显示该任务完成的百分比。

此百分比通常由一个矩形以可视化形式表示,该矩形开始是空的,随着任务的完成逐渐被填充。

在该实例中,在构造方法中设置了图形界面并添加了事件监听器,从而使图形界面具有动态效果,actionPerformed()方法和stateChanged()方法是事件监听器对必须实现的方法,有关事件的详细知识将在下一章中详细介绍。

该实例运行效果如图9-24所示:
图9-24 进度条。

基于Jquery插件Uploadify实现实时显示进度条上传图片

基于Jquery插件Uploadify实现实时显示进度条上传图片

基于Jquery插件Uploadify实现实时显⽰进度条上传图⽚先了解了解Uploadify,具体内容如下Uploadify是⼀个简单易⽤的多⽂件上传⽅案。

作为⼀个Jquery插件,Uploadify使⽤简单,并具有⾼度的定制性。

Uploadify特性:Uploadify简单说来,是基于Jquery的⼀款⽂件上传插件。

它的功能特⾊总结如下:1)、⽀持单⽂件或多⽂件上传,可控制并发上传的⽂件数2)、在服务器端⽀持各种语⾔与之配合使⽤,诸如PHP,.NET,Java……3)、通过参数可配置上传⽂件类型及⼤⼩限制4)、通过参数可配置是否选择⽂件后⾃动上传5)、易于扩展,可控制每⼀步骤的回调函数(onSelect, onCancel……)6)、通过接⼝参数和CSS控制外观7)、提供上传进度的事件回调,实时显⽰上传进度8)、开始之前要先下载插件安装包到本地并引⽤,详细实现请看代码注释,下⾯开始代码。

1、html代码<div id="webApplogo_file" style="display: block; width: 800px; background-color: #fff;"><ul><li style="margin-left: 213px;"><span class="black_blod14">LOGO图标:</span></li><li style="margin-left: 3px;"><input type="text" readonly="readonly" id="text_webApplogo" name="app_logo" class="appipt1" value="<%=applogo %>" /></li><li style="padding-top: 1px;"><input type="file" id="webApplogo" name="webApplogo" /></li><li><span style="display: none; margin-left: 5px; padding-left: 20px; color: #EA5200;font-size: 12px; background: url('Images/icon_03.gif' ) no-repeat 0px 0px;" id="textporApplogo">请上传LOGO图标!</span></li><li style="margin-left: 220px;"><span class="grey999" style="margin-left: 90px; float: left;">尺⼨72px*72px,png格式,建议使⽤图标PSD模板制作</span><div id="QID_webApplogo" class="fileQueue"></div><table id="webApplogo_tab" width="50%" border="0" cellspacing="0" cellpadding="0"align="center" class="grey999" style="display: none; margin-left: 90px; float: left;"><tr><td align="center" valign="bottom"><img style="width: 64px; height: 64px;" id="img_64" src="images/icon_02.gif" border="0" /><br />(64*64)</td><td align="center" valign="bottom"><img style="width: 48px; height: 48px;" id="img_48" src="images/icon_02.gif" border="0" /><br />(48*48)</td><td align="center" valign="bottom"><img style="width: 32px; height: 32px;" id="img_32" src="images/icon_02.gif" border="0" /><br />(32*32)</td><td align="center" valign="bottom"><img style="width: 16px; height: 16px;" id="img_16" src="images/icon_02.gif" border="0" /><br />(16*16)</td></tr></table></li></ul></div>2、Javascript代码(关键部分)$("#webApplogo").uploadify({'uploader': 'js/uploadify-v2.1.4/uploadify.swf',//进度条,Uploadify⾥⾯含有'script': 'UploadApplogo.ashx',//⼀般处理程序'cancelImg': 'js/uploadify-v2.1.4/cancel.png',//取消图⽚路径'folder': 'Imagelogo',//上传⽂件夹名'auto': true, //⽂件添加到上传队列后,⾃动进⾏上传。

JavaScript实现审核流程状态的动态显示进度条

JavaScript实现审核流程状态的动态显示进度条

JavaScript实现审核流程状态的动态显⽰进度条对于有很多流程的东西,我们希望能够根据不同的阶段,⽤流程条对应地进⾏显⽰,如下所⽰:以上功能对应的html代码如下:<div class="col-md-12 col-lg-3"><div class="panel panel-default"><div class="tit06"><h3>漏洞处理状态</h3></div><div class="status"><ul><li name="__tab_step1_pub" class="top active"><div class="info" id="tab_step1"><h4><div class="heading"></div>待审阅</h4><p class="text" >漏洞已提交,等待⼚商审阅</p></div></li><li name="__tab_step2_pub" ><div class="info" id="tab_step2"><h4><div class="heading"></div>待确认</h4><p class="text" >漏洞已开始审阅,等待⼚商确认</p></div></li><li name="__tab_step3_pub"><div class="info" id="tab_step3"><h4><div class="heading"></div>待修复</h4><p class="text" >漏洞已被确认,等待⼚商修复</p></div></li><li name="__tab_step4_pub"><div class="info" id="tab_step4"><h4><div class="heading"></div>已关闭</h4><p class="text" >漏洞修复完毕,⼚商关闭漏洞</p></div></li><li name="__tab_step5_pub" ><div class="info" id="tab_step5"><h4> <div class="heading"></div>已公开</h4><p class="text" >⼚商同意公开此漏洞</p></div></li></ul></div></div></div>这⾥采⽤的⽅法是根据处理的状态,这⾥是$status,对应的在相应的<li>的标签中增加样式类 class="active",⽽样式类active中实现的是在对应位置替换背景图⽚,即将原来的灰⾊流程线条替换成绿⾊的流程线条。

vue+element-ui+axios多文件上传的实现并显示整体进度

vue+element-ui+axios多文件上传的实现并显示整体进度

vue+element-ui+axios多⽂件上传的实现并显⽰整体进度⽬录element-ui+axios多⽂件上传并显⽰进度解决element ui多⽂件上传的问题业务场景解决办法element-ui+axios多⽂件上传并显⽰进度element-ui⾃带的多⽂件上传是做成了多⽂件多次上传,公司有需求需要选取多个⽂件⼀次上传全部.代码部分<template><d2-container><el-form ref="form" :model="formData" label-width="120px"><el-row><el-col :span="10"><el-form-item label="图⽚" prop="mediaFileUrl"><el-upload style="width: 100%;"class="upload-demo"ref="uploadMul"multipleactiondrag:limit="maxUploadSize":on-exceed="uploadLimit":http-request="uploadFile":file-list="fileList":auto-upload="false":on-remove="handleRemove":before-upload="beforeUpload":on-change="uploadChange"><i class="el-icon-upload"></i><div class="el-upload__text">将⽂件拖到此处,或<em>点击上传</em></div><div class="el-upload__tip" slot="tip">⽀持上传jpg/png/gif⽂件,且不超过100M</div></el-upload><div v-show="progressFlag" class="head-img"><el-progress :text-inside="true" :stroke-width="14" :percentage="progressPercent" status="success"></el-progress></div><el-button size="mini" type="success" @click="submitUpload">上传到服务器</el-button><el-button v-if="this.fileList.length > 0" size="mini" type="warning" @click="clearFiles">清空</el-button></el-form-item></el-col><el-col :offset="4"></el-col></el-row></el-form></d2-container></template><script>import axios from 'axios'export default {data () {return {maxUploadSize: 10,progressFlag: false,progressPercent: 10,innerVisible: false,fileList: [],isViewDisabled: false,formData: {},param: {} // 上传⽂件主要参数}},methods: {submitUpload () {if (this.fileList.length < 1) {this.$message.warning('请选择⽂件!')return false}this.$refs.uploadMul.submit()if (this.param instanceof FormData) {// 附加参数this.param.append('expirationsec', 0)this.param.append('fileproperty', 'publicfiles')// const config = {// headers: { 'content-type': 'multipart/form-data' }// }// axios.post('/api/oss/ossUploadObject', this.param, config).then(res => {// if (res.status === 200 && res.data.status === 200) {// this.$message.success('上传成功!')// let result = res.data.body.data// console.log(result)// }// this.$refs.uploadMul.clearFiles()// this.param = {}// })let that = thisthat.progressFlag = trueaxios({url: '/api/oss/ossUploadObject',method: 'post',data: that.param,headers: { 'Content-Type': 'multipart/form-data' },onUploadProgress: progressEvent => {// progressEvent.loaded:已上传⽂件⼤⼩// progressEvent.total:被上传⽂件的总⼤⼩// 进度条that.progressPercent = ((progressEvent.loaded / progressEvent.total) * 100).toFixed(0) | 0 }}).then(res => {this.param = {}this.fileList = []console.log(res)if (res.data.status === 200 && that.progressPercent === 100) {setTimeout(function () {that.$message({message: '上传成功!',type: 'success',duration: '2000'})that.progressFlag = falsethat.progressPercent = 0that.$refs.uploadMul.clearFiles()}, 1000)let result = res.data.body.dataconsole.log(result)} else {setTimeout(function () {that.$message({message: res.data.msg,type: 'error',duration: '2000'})that.progressFlag = falsethat.progressPercent = 0that.$refs.uploadMul.clearFiles()}, 1000)}}).catch(() => {that.progressFlag = falsethat.progressPercent = 0that.$refs.uploadMul.clearFiles()that.$message({message: '上传失败!',type: 'error',duration: '2000'})})} else {console.log(this.param instanceof FormData)}},handleRemove (file, fileList) {this.$message.warning(`已移除⽂件: ${}!`)// 每移除⼀个⽂件,param重新赋值this.param = new FormData()this.fileList = [...fileList]this.fileList.forEach((file, index) => {this.param.append(`file`, file.raw) // 把单个⽂件重命名,存储起来(给后台)})},uploadChange (file, fileList) {// const videoType = ['image/gif', 'image/png', 'image/jpeg', 'video/mp4', 'video/flv', 'video/avi', 'video/rmvb']// if (videoType.indexOf(file.raw.type) === -1) {// this.$message.error(`不⽀持此⽂件格式${file.raw.type}`)// this.$refs.uploadMul.clearFiles()// return false// }this.param = new FormData()this.fileList = [...fileList]this.fileList.forEach((file, index) => {this.param.append(`file`, file.raw) // 把单个⽂件重命名,存储起来(给后台)})},// 超出上传个数时调⽤uploadLimit (files, fileList) {this.$message.error(`最多允许同时上传${this.maxUploadSize}个⽂件!`)// files.forEach((file, index) => {// console.log(index)// })},beforeUpload (file) {},uploadFile (file) {// 该⽅法需存在,防⽌空action时element-ui报404异常},clearFiles () {this.fileList = []this.param = {}this.$refs.uploadMul.clearFiles()},// 初始化表单数据init () {}}}</script><style lang="scss" scoped></style>后端代码(模拟)@RequestMapping("/oss/ossUploadObject")public ApiResponse<FileDto> uploadObject(@RequestParam("file") MultipartFile[] file, FileVo fileVo){//...codeFileDto dto = new FileDto();dto.setUrl("");dto.setFileId("");return ApiResponse.success(FileDto);}解决element ui多⽂件上传的问题业务场景在使⽤vue+elementui 实现⽂件上传的时候,我发现官⽹给的组件每次都会⾃动上传,⽽且⼀次上传⼀个⽂件。

WebUploader,Java大文件分片上传

WebUploader,Java大文件分片上传

Web大文件分片上传Web环境中大文件上传不能再用form表单一次上传了,这样效率太低;我在不断尝试SpringMVC环境下分片接受文件,最终失败;原因目测是SpringMVC、Struts 框架是不支持HTML5方式上传的(这类框架只能支持Form表单方式的文件上传,或者FLash)那我们可以使用Servlet和SpringMVC结合集成方式实现大文件分片上传;一、来看看我们的web.xml的配置很明显两个servlet,上面一个配置的是SpringMVC的入口,下面servlet是视频上传;他们俩的url-pattern不能冲突;二、先来看看WebUploader的前端代码以下是代码:<%@page language="java"contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC"-//W3C//DTD HTML 4.01Transitional//EN""/TR/html4/loose.dtd"><html><head><basehref="${pageContext.request.scheme}://${pageContext.request.serve rName}:${pageContext.request.serverPort}${pageContext.request.context Path}/"><script type="text/javascript"src="webuploader/jquery-1.7.2.js"></scri pt><script type="text/javascript"src="webuploader/webuploader.min.js"></s cript><link href="webuploader/webuploader.css"type="css/text"/></head><body><h2>Hello World!</h2><div id="thelist"class="uploader-list"></div><div style="margin: 20px 20px 20px 0;"><div id="picker"class="form-control-focus">选择文件</div> </div><button id="btnSync"type="button"class="btn btn-warning">开始同步</button><script>var uploader = WebUploader.create({// swf文件路径swf : 'webuploader/Uploader.swf',// 文件接收服务端。

java实现文件上传和下载

java实现文件上传和下载

java实现⽂件上传和下载本⽂实例为⼤家分享了java实现⽂件上传和下载的具体代码,供⼤家参考,具体内容如下⽂件的上传upload:⽂件上传客户端通过表单的⽂件域file 把客户端的⽂件上传保存到服务器的硬盘上页⾯⾸先对上传的表单有以下要求:必须有⽂件域:input type=file表单提交⽅式:method=post表单的 enctype=multipart/form-data<form method="post" action="/user/regist" enctype="multipart/form-data"><table style="border: chartreuse;solid:2px"><tr><th>⽤户名</th><td><input type="text" name="username"></td></tr><tr><th>密码</th><td><input type="password" name="password"></td></tr><tr><th>⽤户头像</th><td><input type="file" name="photo"> </td></tr><tr><td colspan="2"><input type="submit" value="提交"></td></tr></table></form>Servlet1)⾸先要导⼊以下两个jar包,通过commons-fileupload实现⽂件上传2)创建⼀个⼯⼚对象DiskFileItemFactory,在创建⼀个多部件表单解析器ServletFileUpload,构造⽅法传⼊⼯⼚对象3)解析器解析请求对象,获得⼀个list集合,其中list集合存储的是⼀个⼀个的fileItem对象,⼀个fileItem对应⼀个组件,也就是⼀个<input>4) 遍历集合⽤isFormField()⽅法判断是否为普通组件,然后着重处理⽂件域组件5)获取⽂件名,并⽤getRealPath⽅法获取服务器上传⽂件所在路径,创建新⽂件夹6)获取输⼊流和创建输出流,进⾏⽂件的读写@WebServlet(value = "/user/regist")public class UploadServlet extends HttpServlet {protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//创建⼀个⼯⼚对象DiskFileItemFactory factory = new DiskFileItemFactory();//创建⼀个多部件解析器对象ServletFileUpload fileUpload = new ServletFileUpload(factory);User user = new User();FileOutputStream out=null;try {//⽤解析器对象解析请求,返回⼀个FileItem类型的集合List<FileItem> list = fileUpload.parseRequest(req);for (FileItem fileItem : list) {/*** fileItem.getFieldName());:::获取组件的name值* fileItem.getName());::::获取⽂件域的⽂件名* fileItem.getSize());::::获取数据的字节个数* fileItem.getString());::::获取数据的字符串* fileItem.isFormField());:::判断是否为普通组件*///判断部件是否为普通组件if (fileItem.isFormField()) {//普通组件//获取组件名字也就是name的值String fieldName = fileItem.getFieldName();//获取组件的值也就是value的值String value = fileItem.getString("utf-8");if ("username".equals(fieldName)) { //设置实体类的属性user.setUsername(value);} else if ("password".equals(fieldName)) {user.setPassword(value);}} else {// ⽂件域//获取⽂件名String fielName = fileItem.getName();//输⼊流来读数据InputStream in = fileItem.getInputStream();//设置⽂件写出的路径,并⽤随机码来保证图⽚可以重复String path=req.getServletContext().getRealPath("/imgs/"+ UUID.randomUUID()+fielName);System.out.println("⽂件路径为:"+path);File file = new File(path);out = new FileOutputStream(file);//利⽤commons-io-1.4.jar的IOUtils的copy⽅法直接实现⽂件的复制IOUtils.copy(in,out);user.setPhoto(file.getName());}}} catch (Exception e) {e.printStackTrace();}finally {if(out!=null){out.close();}}req.getSession().setAttribute("user",user);req.getRequestDispatcher("/sucess.jsp").forward(req,resp);}}⽂件的下载页⾯只需⼀个超链接,传需要下载的⽂件名,或者直接输⼊路径在浏览器例: <a href="<c:url value='/file/download?fileName=14.jpg'/>" >狗狗1</a><br/>Servlet1)接收参数,获取⽂件名2)获取imgs的路径,也就是存储⽂件的⽂件夹的路径,然后创建⽂件,传⼊该路径和⽂件名3)创建输⼊流读取⽂件4)设置响应头,⾸先根据⽂件名字获取⽂件的⼤类型,设置响应头Content-Type指定响应的类型;设置响应头Content-Disposition,指定⽂件以附件形式保存到本地磁盘5)⽤响应获取输出流,读出⽂件到客户端@WebServlet("/user/download")public class DownloadServlet extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("UTF-8");//获取要下载的⽂件名String fileName = request.getParameter("fileName");System.out.println(fileName);//获取服务器中存储图⽚的⽂件夹的路径String path1 = request.getServletContext().getRealPath("/imgs");String path=path1+"/"+fileName;File file = new File(path);//创建输⼊流读⽂件FileInputStream in = new FileInputStream(file);//通过⽂件名字获取⽂件的⼤类型String type = request.getServletContext().getMimeType(fileName);//设置响应头ContentType指定响应内容的类型response.setHeader("Content-type",type);//设置响应头Content-Disposition 指定以附件形式保存响应的信息response.setHeader("Content-Disposition","attachment;filename="+(URLEncoder.encode(fileName, "utf-8"))); ServletOutputStream out = response.getOutputStream();//实现⽂件的读写IOUtils.copy(in,out);if(in!=null){in.close();}}}以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

批量上传文件及进度显示

批量上传文件及进度显示

//监听用于上传显示进度
47
var xhr = $.ajaxSettings.xhr();
48
if(onprogress && xhr.upload) {
49
xhr.upload.addEventListener("progress" , onprogress, false);
50
return xhr;
41
processData : false,
42
//必须false才会自动加上正确的Content-Type
43
44
45
46
*/
contentType : false ,
/* beforeSend:beforeSend,//发送请求
complete:complete,//请求完成
xhr: function(){
34
formData.append('files', ss[j]); //将该file对象添加到formData对象中
35
$.ajax({
36
url:'fileUpLoad.action',
37
type:'POST',
38
cache: false,
39
data:{},//需要什么参数,自己配置
40
data: formData,//文件以formData形式传入
</li>");
23
24
}
25
sendAjax();
26
function sendAjax() {
27
if(j>=ss.length) //采用递归的方式循环发送ajax请求

Nodejs文件上传、监听上传进度的代码

Nodejs文件上传、监听上传进度的代码

Nodejs⽂件上传、监听上传进度的代码前⾔⽂件上传如果加上进度条会有更好的⽤户体验(尤其是中⼤型⽂件),本⽂使⽤Nodejs 配合前端完成这个功能。

前端我们使⽤FormData 来作为载体发送数据。

效果前端部分HTML 部分和 Js 部分<input type="file" id="file" /><!-- 进度条 --><progress id="progress" value="0" max="100"></progress>// 获取 input file 的 dom 对象const inputFile = document.querySelector('#file');// 监听 change 事件inputFile.addEventListener('change', function() {// 使⽤ formData 装载 fileconst formData = new FormData();formData.append('file', this.files[0]);// 上传⽂件upload(formData);})下⾯我们实现 upload ⽅法。

使⽤ XMLHttpRequest 的⽅式const upload = ( formData ) => {const xhr = new XMLHttpRequest();// 监听⽂件上传进度xhr.upload.addEventListener('progress', function(e) {if (e.lengthComputable) {// 获取进度const progress = Math.round((e.loaded * 100) / e.total);document.querySelector('#progress').setAttribute('value', progress);}},false);// 监听上传完成事件xhr.addEventListener('load', ()=>{console.log(':smile:上传完成')}, false);xhr.open('post', 'http://127.0.0.1:3000/upload');xhr.send(formData);}使⽤ jQuery 的 ajax 上传jQuery ⽬前的使⽤量依然庞⼤,那么使⽤ jQuery 的 ajax 如何监听⽂件上传进度呢:const upload = ( formData ) => {$.ajax({type: 'post',url: 'http://127.0.0.1:3000/upload',data: formData,// 不进⾏数据处理和内容处理processData: false,contentType: false,// 监听 xhrxhr: function() {const xhr = $.ajaxSettings.xhr();if (xhr.upload) {xhr.upload.addEventListener('progress', e => {const { loaded, total } = e;var progress = (loaded / total) * 100;document.querySelector('#progress').setAttribute('value', progress);},false);return xhr;}},success: function(response) {console.log('上传成功');}});}使⽤ axios 上传并监听进度axios 使⽤量⾮常⼤,⽤它监听⽂件上传更简单,代码如下:const upload = async ( formData ) => {let config = {// 注意要把 contentType 设置为 multipart/form-dataheaders: {'Content-Type': 'multipart/form-data'},// 监听 onUploadProgress 事件onUploadProgress: e => {const {loaded, total} = e;// 使⽤本地 progress 事件if (e.lengthComputable) {let progress = loaded / total * 100;document.querySelector('#progress').setAttribute('value', progress);}}};const { status } = await axios.post('http://127.0.0.1:3000/upload', formData, config);if (res.status === 200) {console.log('上传完成:grinning:');}}Nodejs 部分这部分⽐较简单,其实就是单纯的⽂件上传,我们⽤ Koa 来实现.环境搭建及依赖包安装这⾥使⽤ koa2 ,安装以下依赖包:koa@koa/router: koa 的路由@koa/cors:⽤于跨域koa-body: 解析 body 数据nodemon: 使⽤它启动服务,带有热更新代码部分const Koa = require('koa');const Router = require('@koa/router');const koaBody = require('koa-body');const path = require('path');const fs = require('fs');const cors = require('@koa/cors');const app = new Koa();const router = new Router();router.all('/upload', async ctx => {// 处理⽂件上传const res = await dealFile(ctx);res && (ctx.body = {status: 200,msg: 'complete'});});// 中间件部分e(cors());e(koaBody({multipart: true,formidable: {maxFileSize: 2000 * 1024 * 1024 //最⼤2G}}));e(router.routes());e(router.allowedMethods());app.listen(3000);dealFile ⽅法处理上传的⽂件出于性能考虑,操作 file 毫⽆疑问要使⽤ stream 。

实现在下载文件过程显示进度条,简单例子

实现在下载文件过程显示进度条,简单例子

实现在下载⽂件过程显⽰进度条,简单例⼦package com.file;import java.io.*;import java.text.DecimalFormat;import java.util.ArrayList;// 使⽤java实现在下载⽂件的过程中显⽰进度条public class TestFile {public static class ProgressBarThread implements Runnable {private ArrayList<Integer> proList = new ArrayList<Integer>();private int progress; //当前进度private int totalSize; //总⼤⼩private boolean run = true;public ProgressBarThread(int totalSize) {this.totalSize = totalSize;//TODO 创建进度条}/*** @param progress 进度*/public void updateProgress(int progress) {synchronized (this.proList) {if (this.run) {this.proList.add( progress );this.proList.notify();}}}public void finish() {this.run = false;//关闭进度条}@Overridepublic void run() {synchronized (this.proList) {try {while (this.run) {if (this.proList.size() == 0) {this.proList.wait();}synchronized (proList) {this.progress += this.proList.remove( 0 );//TODO 更新进度条DecimalFormat decimalFormat = new DecimalFormat( "0.00" );System.err.println( "当前进度:" + decimalFormat.format( this.progress / (float) this.totalSize * 100 ) + "%" );}}System.out.println( "下载完成" );} catch (Exception e) {e.printStackTrace();}}}}}测试代码// 测试public static void main(String[] args) {try {File file = new File( "/Users/zhenning/Documents/tools/mysql51.docset.zip" );FileInputStream fis = new FileInputStream( file );FileOutputStream fos = new FileOutputStream( "/Users/zhenning/Desktop/mysql51.docset.zip" );ProgressBarThread pbt = new ProgressBarThread( (int) file.length() );//创建进度条new Thread( pbt ).start();//开启线程,刷新进度条byte[] buf = new byte[1024];int size = 0;while ((size = fis.read( buf )) > -1) { //循环读取fos.write( buf, 0, size );pbt.updateProgress( size );//写完⼀次,更新进度条}pbt.finish(); //⽂件读取完成,关闭进度条fos.flush();fos.close();fis.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}//// 测试public static void main(String[] args) {HttpClient httpClient = new DefaultHttpClient();try {HttpResponse resp = httpClient.execute( new HttpPost( "/issue/netdisk/MACguanjia/BaiduNetdisk_mac_3.4.1.dmg" ) ); HttpEntity entity = resp.getEntity();int length = (int) entity.getContentLength();//这个就是下载的⽂件(不单指⽂件)⼤⼩InputStream is = entity.getContent();ProgressBarThread pbt = new ProgressBarThread( length );//创建进度条new Thread( pbt ).start(); //开启线程,刷新进度条byte[] buf = new byte[1024];int size = 0;FileOutputStream fos = new FileOutputStream( new File( "/Users/zhenning/Desktop/BaiduNetdisk_mac_3.4.1.dmg" ) ); //while ((size = is.read( buf )) > -1) { //循环读取fos.write( buf, 0, size );pbt.updateProgress( size );//写完⼀次,更新进度条}pbt.finish(); //⽂件读取完成,关闭进度条fos.flush();fos.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}。

Java通用文件上传功能实现

Java通用文件上传功能实现

Java通用文件上传功能实现一、文件上传流程说明:Java文件上传功能是指在Java开发中,实现文件上传的功能,可以用于各种场景,如网站上传图片、文件管理系统等。

以下是一种常见的实现方式:1、创建一个包含文件上传功能的表单页面,用户可以选择要上传的文件并提交表单。

2、在后端Java代码中,接收表单提交的文件数据。

可以使用Apache Commons FileUpload库或Spring框架提供的MultipartFile类来处理文件上传。

3、对接收到的文件进行处理,可以将文件保存到服务器的指定位置,或者将文件存储到数据库中。

4、返回上传成功或失败的信息给用户。

二、代码实现,方案一:在Java中实现文件上传功能可以通过以下步骤来完成:1、创建一个HTML表单,用于选择要上传的文件:<form action="upload"method="post" enctype="multipart/form-data"> <input type="file" name="file" /><input type="submit" value="Upload" /></form>2、创建一个Servlet或者Controller来处理文件上传请求:@WebServlet("/upload")public class UploadServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) {// 获取上传的文件Part filePart = request.getPart("file");String fileName = filePart.getSubmittedFileName();// 指定上传文件的保存路径String savePath = "C:/uploads/" + fileName;// 将文件保存到指定路径filePart.write(savePath);// 返回上传成功的消息response.getWriter().println("File uploaded successfully!");}}3、配置web.xml(如果使用传统的Servlet方式)或者使用注解(如果使用Servlet 3.0+)来映射Servlet。

elementel-upload自定义上传显示进度条,多文件上传进度

elementel-upload自定义上传显示进度条,多文件上传进度

elementel-upload⾃定义上传显⽰进度条,多⽂件上传进度<template><div><el-uploadclass="upload-demo"ref="upload":multiple="false"action="void":http-request="customUpload":on-remove="handleRemove":on-progress="progressA":file-list="fileList"multiple:auto-upload="true"><el-button slot="trigger" size="small" type="primary">选取⽂件</el-button></el-upload></div></template><script>export default {data() {return {fileList: [],}},components: {},mounted() {},methods: {customUpload(file) {let FormDatas = new FormData();FormDatas.append('file', file.file);this.$axios({url: 'http://192.168.1.5:8889/upload',method: 'post',data: FormDatas,//上传进度onUploadProgress: (progressEvent) => {let num = progressEvent.loaded / progressEvent.total * 100 | 0; //百分⽐file.onProgress({percent: num}) //进度条}}).then(data => {file.onSuccess(); //上传成功(打钩的⼩图标)})},/** ⽂件正在上传时的钩⼦ **/progressA(event, file) {},/** 移除上传⽂件 **/handleRemove(file) {this.$refs.upload.abort(); //取消上传this.$message({message: '成功移除' + , type: 'success'});},},}</script><style></style>。

JS-JQuery-使用input实现文件上传(type=file)且有进度条(onpro。。。

JS-JQuery-使用input实现文件上传(type=file)且有进度条(onpro。。。

JS-JQuery-使⽤input实现⽂件上传(type=file)且有进度条(onpro。

在另⼀篇⾥已经说了如何实现type="file"的input⽂件上传,现新增需求需要展⽰上传的进度,所以在原来基础上再加上先看效果展⽰:1、⾸先还是先添加html<!-- 上传按钮 --><div class="fileBtn" id="uploadBtn"><input type="file" id="uploadfile"><button type="button" class="btn btn-primary btn-sm btn-flie">上传附件</button></div><!-- ⽂件信息 --><div class="info-item" id="fileList"><!-- <div class="files-info"> <p>⽂件1.pdf</p><p class="filedown checkIcon"><img src="images/check.png" alt=""></p><p class="filedown downIcon"><img src="images/down.png" alt=""></p><p class="filedown deleteIcon"><img src="images/del.png" alt=""></p></div> --></div><!-- 进度条 --><div class="progressBox" id="progressBox"><div class="progressItem"><div class="progressBar" id="progressBar"></div><div class="progressText" id="progressText">0%</div></div></div>2、css样式.fileBtn {position:relative;}.fileBtn #uploadfile {width: 120px;height: 30px;filter: Alpha(opacity=0);-moz-opacity:0;opacity: 0;position: absolute;z-index: 2;}.fileBtn .btn-flie {width: 120px;height: 30px;position: absolute;z-index: 1;}.info-item {margin-top: 30px;}.progressBox{margin-top: 35px;width: 50%;height: 10px;background: #fff;display: block;}.progressBox .progressItem {width: 100%;height: 100%;border: 1px solid #ccc;border-radius: 5px;position: relative;}.progressBox .progressBar{width: 0;height: 100%;background: #337ab7;border-radius: 5px;position: absolute;top: 0;left: 0;}.progressBox .progressText{font-size: 14px;color: #337ab7;position: absolute;top: -7px;right: -50px;}3、js相关代码var fileList = [] // ⽂件list$('#uploadfile').change(function(){// 初始化进度条状态// $('#progressBox').css("display","block")$('#progressBar').css('width','0%');$('#progressText').text('0%');var fileItem = $('#uploadfile')[0].files[0]var formData = new FormData();formData.append('file', fileItem)formData.append('type', '1')$.ajax ({type : "post",url : "/user/upload",data : formData,async : true,cache : false,contentType : false,//需设置为false,因为是FormData对象,且已经声明了属性enctype="multipart/form-data" processData : false,//需设置为false,因为data值是FormData对象,不需要对数据做处理dataType : 'json',xhr: function() {var xhr = $.ajaxSettings.xhr();if (xhr.upload) {xhr.upload.addEventListener("progress", function (e) {var loaded = e.loaded; //已经上传⼤⼩情况var tot = e.total; //附件总⼤⼩var per = Math.floor(100 * loaded / tot); //已经上传的百分⽐$('#progressBar').css('width',per+'%'); //这⾥指的是进度条的宽度等于完成的百分⽐$('#progressText').text(per+'%'); //显⽰进度百分⽐}, false);return xhr;}},success : function (data) {if (data.code == 2000){var dataInfo = data.dataif(dataInfo) {toastr.success('上传成功'); // 提⽰上传成功插件-可以更换与不⽤// $('#progressBox').css("display","none") // 这句是上传成功后将进度条隐藏,看⾃⼰需求是否需要// 重置进度条$('#progressBar').css('width','0%');$('#progressText').text('0%');setTimeout(function(){toastr.clear();}, 1000);fileList.push(dataInfo)showFile()}} else{alert(data.message);}},error : function(data) {toastr.error('上传失败');// $('#progressBox').css("display","none")setTimeout(function(){toastr.clear();}, 1000);}});});function showFile() {// 展⽰⽂件信息var fileItem = fileListif(fileItem.length){var str = ''for(var i = 0; i < fileItem.length; i++){str += '<div class="files-info"><div>';str += fileItem[i].namestr += '</div>'str += '<div class="iconGroup">'str += '<p class="filedown downLoad"><img src="images/down.png" alt="" onclick=downFileItem('str += "\'";str += fileItem[i].url;str += "\'";str += ')></p>';if(status!=1&&status!=3){str += '<p class="filedown delete"><img src="images/del.png" alt="" onclick=delFileItem('str += "\'";str += i;str += "\'";str += ')></p>';}str += '</div>';str += '</div>';}$('#fileList').html(str)} else {$('#fileList').empty() }};。

RxJava+Retrofit+OkHttp实现文件上传

RxJava+Retrofit+OkHttp实现文件上传

RxJava+Retrofit+OkHttp实现⽂件上传背景在实际运⽤中上传是⼀个必不可少的功能,所以我们在封装⼆的基础上加⼊上传的功能,同时需要附带上传进度!效果实现1.定义service接⼝注意:Multipart是指定⼤⽂件上传过程中的标⽰,⼀般上传图⽚的过程中我们需要附带信息,所以我们需要⽤到@part指定传递的数值,MultipartBody.Part是指定传递的⽂件;/*上传⽂件*/@Multipart@POST("AppYuFaKu/uploadHeadImg")Observable<BaseResultEntity<UploadResulte>> uploadImage(@Part("uid") RequestBody uid, @Part("auth_key") RequestBody auth_key,@Part MultipartBody.Part file);2.加⼊进度条retrofit是基于okhttp的处理,所以我们可以⾃定义RequestBody,复写writeTo(BufferedSink sink)⽅法,得到传递的进度数据public class ProgressRequestBody extends RequestBody {//实际的待包装请求体private final RequestBody requestBody;//进度回调接⼝private final UploadProgressListener progressListener;//包装完成的BufferedSinkprivate BufferedSink bufferedSink;public ProgressRequestBody(RequestBody requestBody, UploadProgressListener progressListener) {this.requestBody = requestBody;this.progressListener = progressListener;}/*** 重写调⽤实际的响应体的contentType* @return MediaType*/@Overridepublic MediaType contentType() {return requestBody.contentType();}/*** 重写调⽤实际的响应体的contentLength* @return contentLength* @throws IOException 异常*/@Overridepublic long contentLength() throws IOException {return requestBody.contentLength();}/*** 重写进⾏写⼊* @param sink BufferedSink* @throws IOException 异常*/@Overridepublic void writeTo(BufferedSink sink) throws IOException {if (null == bufferedSink) {bufferedSink = Okio.buffer(sink(sink));}requestBody.writeTo(bufferedSink);//必须调⽤flush,否则最后⼀部分数据可能不会被写⼊bufferedSink.flush();}/*** 写⼊,回调进度接⼝* @param sink Sink* @return Sink*/private Sink sink(Sink sink) {return new ForwardingSink(sink) {//当前写⼊字节数long writtenBytesCount = 0L;//总字节长度,避免多次调⽤contentLength()⽅法long totalBytesCount = 0L;@Overridepublic void write(Buffer source, long byteCount) throws IOException {super.write(source, byteCount);//增加当前写⼊的字节数writtenBytesCount += byteCount;//获得contentLength的值,后续不再调⽤if (totalBytesCount == 0) {totalBytesCount = contentLength();}Observable.just(writtenBytesCount).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<Long>() {@Overridepublic void call(Long aLong) {progressListener.onProgress(writtenBytesCount, totalBytesCount);}});}};}}3⾃定义接⼝,回调progress进度public interface UploadProgressListener {/*** 上传进度* @param currentBytesCount* @param totalBytesCount*/void onProgress(long currentBytesCount, long totalBytesCount);}4创建RequestBody对象,加⼊进度File file=new File("/storage/emulated/0/Download/11.jpg");RequestBody requestBody=RequestBody.create(MediaType.parse("image/jpeg"),file);MultipartBody.Part part= MultipartBody.Part.createFormData("file_name", file.getName(), new ProgressRequestBody(requestBody,new UploadProgressListener() {@Overridepublic void onProgress(long currentBytesCount, long totalBytesCount) {tvMsg.setText("提⽰:上传中");progressBar.setMax((int) totalBytesCount);progressBar.setProgress((int) currentBytesCount);}}));5.传递附带信息和封装⼆中post请求的⽅式⼀样,我们需要继承baseentity,复写⾥⾯的⽅法,然后设置需要传递的参数,因为是测试接⼝,所以我的参数直接写死在entity⾥⾯,part⽂件动态指定/*** 上传请求api* Created by WZG on 2016/10/20.*/public class UplaodApi extends BaseEntity {/*需要上传的⽂件*/private MultipartBody.Part part;public UplaodApi(HttpOnNextListener listener, RxAppCompatActivity rxAppCompatActivity) {super(listener, rxAppCompatActivity);setShowProgress(true);}public MultipartBody.Part getPart() {return part;}public void setPart(MultipartBody.Part part) {this.part = part;}@Overridepublic Observable getObservable(HttpService methods) {RequestBody uid= RequestBody.create(MediaType.parse("text/plain"), "4811420");RequestBody key = RequestBody.create(MediaType.parse("text/plain"), "21f8d9bcc50c6ac1ae1020ce12f5f5a7");return methods.uploadImage(uid,key,getPart());}}6.post请求处理请求和封装⼆中的请求⼀样,通过传递⼀个指定的HttpOnNextListener 对象来回调来监听结果信息,⼀⼀对应private void uploadeDo(){File file=new File("/storage/emulated/0/Download/11.jpg");RequestBody requestBody=RequestBody.create(MediaType.parse("image/jpeg"),file);MultipartBody.Part part= MultipartBody.Part.createFormData("file_name", file.getName(), new ProgressRequestBody(requestBody, new UploadProgressListener() {@Overridepublic void onProgress(long currentBytesCount, long totalBytesCount) {tvMsg.setText("提⽰:上传中");progressBar.setMax((int) totalBytesCount);progressBar.setProgress((int) currentBytesCount);}}));UplaodApi uplaodApi = new UplaodApi(httpOnNextListener,this);uplaodApi.setPart(part);HttpManager manager = HttpManager.getInstance();manager.doHttpDeal(uplaodApi);}/*** 上传回调*/HttpOnNextListener httpOnNextListener=new HttpOnNextListener<UploadResulte>() {@Overridepublic void onNext(UploadResulte o) {tvMsg.setText("成功");Glide.with(MainActivity.this).load(o.getHeadImgUrl()).skipMemoryCache(true).into(img);}@Overridepublic void onError(Throwable e) {super.onError(e);tvMsg.setText("失败:"+e.toString());}};以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

java中oss的progressupdate的方法

java中oss的progressupdate的方法

java中oss的progressupdate的方法【原创实用版4篇】目录(篇1)I.Java OSS简介II.OSS的ProgressUpdate方法III.ProgressUpdate方法的使用IV.总结正文(篇1)I.Java OSS简介Java OSS(Object Storage Service)是阿里云提供的一种对象存储服务,它允许用户将任意类型的数据存储到云端,并可以通过URL进行访问。

Java OSS提供了简单易用的API,开发者可以使用这些API将数据上传到OSS,也可以使用这些API从OSS下载数据。

II.OSS的ProgressUpdate方法ProgressUpdate方法是Java OSS中的一个重要方法,它用于更新上传或下载数据的进度。

在使用Java OSS上传或下载数据时,可以通过调用ProgressUpdate方法来获取上传或下载的进度信息。

ProgressUpdate 方法需要传入一个参数,即上传或下载数据的进度百分比。

III.ProgressUpdate方法的使用在使用ProgressUpdate方法时,需要传入一个ProgressListener接口的实现类。

ProgressListener接口定义了一个抽象方法,即progressListener(),它用于获取上传或下载的进度信息。

在使用Java OSS上传或下载数据时,可以将ProgressListener接口的实现类传递给ProgressUpdate方法,从而获取上传或下载的进度信息。

IV.总结Java OSS的ProgressUpdate方法是上传或下载数据时获取进度信息的重要方法。

目录(篇2)I.Java中OSS概述II.OSS的ProgressUpdate方法III.ProgressUpdate方法的应用场景IV.ProgressUpdate方法的优点和缺点正文(篇2)Java中OSS(Object Storage Service)是一种广泛使用的云存储服务,可以轻松实现大规模数据的存储和管理。

使用Java快速实现进度条(转)

使用Java快速实现进度条(转)

使⽤Java快速实现进度条(转)[java]1. package org.ubird;2.3. import java.awt.BorderLayout;4. import java.awt.Dimension;5. import java.awt.Image;6. import java.awt.event.ActionEvent;7. import java.awt.event.ActionListener;8. import java.util.ArrayList;9. import java.util.List;10. import java.util.concurrent.ExecutionException;11.12. import javax.imageio.ImageIO;13. import javax.swing.ImageIcon;14. import javax.swing.JButton;15. import javax.swing.JLabel;16. import javax.swing.JPanel;17. import javax.swing.JProgressBar;18. import javax.swing.JScrollPane;19. import javax.swing.SwingUtilities;20. import javax.swing.SwingWorker;21.22. public class TestSwingWorker extends SwingWorker<List<Image>,String>{23.24. private JLabel status;25. private JPanel viewer;26. private String[] imagesName;27. private JProgressBar jpb;28.29. public static void main(String[] args) {30. SwingUtilities.invokeLater(new Runnable(){31. public void run() {32. TestFrame frame = new TestFrame();33. final JPanel panel = new JPanel();34. final JLabel label = new JLabel();35.36. final String[] imagesName = new String[38];37. for(int i=0; i<imagesName.length; i++){38. imagesName[i] = "res/1 ("+(i+1)+").jpg";39. }40.41. JScrollPane sp = new JScrollPane(panel);42. sp.setSize(new Dimension(700,500));43. frame.add(sp,BorderLayout.CENTER);44.45. JPanel stp = new JPanel();46. final JProgressBar jpb = new JProgressBar();47. jpb.setMinimum(1);48. jpb.setMaximum(imagesName.length);49. stp.add(jpb);50. stp.add(label);51. frame.add(stp,BorderLayout.SOUTH);52.53. JButton button = new JButton("load image");54. button.addActionListener(new ActionListener(){55. public void actionPerformed(ActionEvent e) {56. TestSwingWorker sw = new TestSwingWorker(label, panel, imagesName, jpb);57. sw.execute();58. }59. });60.61. frame.add(button,BorderLayout.NORTH);62.63. frame.setVisible(true);64. }65. });66. }67.68. public TestSwingWorker(JLabel status, JPanel viewer, String[] imagesName, JProgressBar jpb){69. this.status = status;70. this.viewer = viewer;71. this.imagesName = imagesName;72. this.jpb = jpb;73. }74.75. @Override76. protected List<Image> doInBackground() throws Exception {77. List<Image> image = new ArrayList<Image>();78. for(int i=0; i<imagesName.length; i++){79. image.add(ImageIO.read(getClass().getClassLoader().getResource(imagesName[i])));80. publish("已经加载了 "+(i+1)+"/"+imagesName.length+" : "+imagesName[i]);81. }82. return image;83. }84.85. @Override86. protected void process(List<String> chunks) {87. status.setText(chunks.get(chunks.size()-1));88. int x = Integer.parseInt(chunks.get(chunks.size()-1).substring(chunks.get(chunks.size()-1).indexOf("(")+1,chunks.get(chunks.size()-1).indexOf(")")).trim());89. jpb.setValue(x);90.91. for(String str : chunks){92. System.out.println(str);93. }94. }95.96. @Override97. protected void done() {98. try {99. for(Image image : get()){100. JLabel label = new JLabel(new ImageIcon(image));101. label.setSize(160, 120);102. label.setPreferredSize(new Dimension(160,120));103. viewer.add(label);104. }105. } catch (InterruptedException e) {106. e.printStackTrace();107. } catch (ExecutionException e) {108. e.printStackTrace();109. }110. }111.112.113. }[java]1. package org.ubird;2.3. import javax.swing.JFrame;4.5. public class TestFrame extends JFrame {6.7.8. public TestFrame(){9. setTitle("Test Frame");10. setSize(800,600);11. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);12. }13. }该程序的可运⾏源码、资源图⽚的下载地址:NOTE:解压后双击⾥⾯的:CompileAndRun.bat可在Win下直接运⾏/kakashi8841/article/details/6388797。

FormData上传文件带进度条

FormData上传文件带进度条

FormData上传⽂件带进度条* jQuery ajax FormData 上传⽂件 template$.ajax({url: url,type: 'POST',data: new FormData(form),dataType: 'json',cache: false,processData: false,contentType: false,}).done(function(data) {myalert.success("视频⽂件上传成功", true); // 提⽰信息不消失console.log(data);return false;}).fail(function(jqXHR, textStatus, errorThrown) {});关键的3个选项: cache: false,processData: false,contentType: false,* demo:<html><head><meta charset="UTF-8"><title>上传校长寄语视频</title><link rel="stylesheet" href="../assets/bootstrap/css/bootstrap.min.css"><style>#wrapper {width: 500px;}.form-control {margin-bottom: 20px;}.btn-primary {margin-left: 70px;width: 170px;}iframe {width: 0;height: 0;border: 0;}.invisible {display: none;}#alert {position: fixed;top: 20px;right: 20px;z-index: 2;}#wrapper ul {margin: 20px 0;}li {list-style: none;}.ui-widget-header {border: 1px solid #ACD978;background: #A1D16B;}#progressbar {border: none;}</style></head><body><div class="container" id="wrapper"><form method="POST" enctype="multipart/form-data"><div class="form-group"><label for="schoolName">学校名称:</label><input class="form-control" id="schoolName" type="text" name="schoolName" /></div><div class="form-group"><label for="file">选择⽂件:</label><input id="file" class="form-control" type="file" name="file" /></div><div class="form-group"><button type="submit" class="btn btn-primary">上传</button></div></form><div id="progressbar"></div><ul><li id="fileName"></li><li id="fileSize"></li><li id="fileType"></li><li id="progressNumber"></li></ul></div><iframe id="J_iframe" name="demoIframe" class="invisible"></iframe><!-- TODO: 播放预览 --><video class="invisible" width="320" height="240" src="http://47.92.133.100:8089/dd.mp4" controls="controls"></video> <script type="text/javascript" src="../assets/ckeditor/js/require.js"></script><script type="text/javascript" src="./js/config.js"></script><script>var form = document.forms[0];form.action = window.CONTEXT_PATH + "/school/uploadMasterVideo";// form.target = "demoIframe";require(['jquery', 'alert', 'jquery-ui'], function($, m) {$("#file").on("change", function() {var file = this;var fileSize = 0;if (file.size > 1024 * 1024) {fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';} else {fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';}var index = stIndexOf("/")if (index < 0) {index = stIndexOf("\\");}var filename = file.value.substring(index + 1);document.getElementById('fileName').innerHTML = '⽂件名: ' + filename;document.getElementById('fileSize').innerHTML = '⽂件⼤⼩: ' + fileSize;document.getElementById('fileType').innerHTML = '⽂件类型: ' + file.type;console.log(file.size);});var myalert = m.alert.getInstance();var $progressbar = $("#progressbar").show();form.onsubmit = function(e) {e.preventDefault();var url = this.action,fd = new FormData(form);/*$.ajax({url: url,type: 'POST',data: new FormData(form),dataType: 'json',cache: false,processData: false,contentType: false,}).done(function(data) {myalert.success("视频⽂件上传成功", true); // 提⽰信息不消失console.log(data);return false;}).fail(function(jqXHR, textStatus, errorThrown) {});*/// 进度百分⽐var p = document.getElementById('progressNumber');var xhr = new XMLHttpRequest();if (!xhr) {document.write("<h1>当前浏览器不⽀持上传⽂件</h1>");return false;}xhr.upload.addEventListener("progress", function(evt) {var text, s = "进度: ",percentComplete;if (evt.lengthComputable) {percentComplete = Math.round(evt.loaded * 100 / evt.total); s += percentComplete.toString() + '%';$progressbar.progressbar("value", percentComplete);} else {s += '⽆法计算';}text = document.createTextNode(s);p.innerHTML = "";p.append(text);if (percentComplete === 100) {("视频处理中...");}}, false);xhr.addEventListener("load", function(evt) {/* 当服务器响应后,这个事件就会被触发 */var txt = evt.target.responseText;console.log(txt);var resp = JSON.parse(txt);if (resp.status === 200) {myalert.success("视频⽂件上传成功", true);} else {myalert.fail(resp.msg, resp.error);}}, false);xhr.addEventListener("error", function() {myalert.fail("上传⽂件发⽣了错误尝试");}, false);xhr.addEventListener("abort", function() {myalert.fail("上传被⽤户取消或者浏览器断开连接");}, false);xhr.open("POST", url);xhr.send(fd);("视频⽂件上传中...");};});require(['jquery', 'jquery-cookie'], function($) {$("#schoolName").val($.cookie("schoolName"));// iframe上传⽂件 cross domain x$("#J_iframe").on("load", function() {var s = this.contentDocument.body.textContent;var resp = JSON.parse(s) || {};console.log(resp);});});require(['jquery', 'jquery-ui'], function($) {css("../assets/jqui/jquery-ui.css");var schoolNames = [];$.ajax({type: 'GET',url: window.CONTEXT_PATH + '/system/school/archive',}).done(function(data) {// for autocomplete, school name listdata.entity.forEach(function(ent) {schoolNames.push();});});$("#progressbar").progressbar({value: 0});$("#schoolName").autocomplete({source: schoolNames,autoFocus: true});});</script></body></html>alert.js(function() {var m = function(timeout) {this.timeout = timeout ? timeout : 3000;var a = document.createElement("div");a.id = "alert";a.className = "alert alert-danger";a.innerHTML = "An error occurred during submitting...";a.style.display = 'none';document.body.append(a);this.$alert = a;};m.getInstance = function() {if (!this.$alert) {this.$alert = new m();}return this.$alert;};m.prototype.success = function(msg, b) {var self = this;self.$alert.className = "alert alert-success";self.$alert.innerHTML = msg;self.$alert.style.display = 'inline-block';if (typeof b !== "undefined" && b) {} else {setTimeout(function() {self.$alert.style.display = "none";}, self.timeout);}};m.prototype.fail = function(msg) {var self = this;self.$alert.className = "alert alert-danger";self.$alert.innerHTML = msg;self.$alert.style.display = 'inline-block';setTimeout(function() {self.$alert.style.display = "none";}, self.timeout);}; = function(msg) {var self = this;self.$alert.className = "alert alert-info";self.$alert.innerHTML = msg;self.$alert.style.display = 'inline-block';};define({ alert: m });})(); config.js// require.js 依赖的js库路径配置require.config({paths : {// "jquery-1.12" : "../assets/jqui/external/jquery/jquery", "jquery-ui": "../assets/jqui/jquery-ui",// "jquery": "../assets/bootstrap/js/jquery-3.3.1.min","jquery": "../assets/ckeditor/js/jquery-3.2.1","ckeditor-core": "../assets/ckeditor/ckeditor",'ckeditor-jquery': "../assets/ckeditor/adapters/jquery", "jquery-cookie": "../assets/js/jquery.cookie","bootstrap": "../assets/bootstrap/js/bootstrap","alert": "js/lib/alert","supersized": "../assets/js/login/supersized.3.2.7","url-param": "js/util/getUrlParam",'image-preview': 'js/util/preview'},shim: {'ckeditor-jquery':{deps:['jquery','ckeditor-core']},'jquery-cookie': {deps: ['jquery']},'bootstrap': {deps: ['jquery']},'jquery-ui':{deps: ['jquery']}}});// 后台ajax url前缀var CONTEXT_PATH = "http://192.168.10.137:9999"; // var CONTEXT_PATH = "http://zhanghum:9999"; 。

layui的上传视频文件添加进度条

layui的上传视频文件添加进度条

layui的上传视频⽂件添加进度条1.在表单上传组件中,添加⽂件上传的主键按钮:2.选⽤⽂档中的上传⽂件进度的回调:我⾃⼰的代码::::(html代码)<div class="layui-form-item"><label class="layui-form-label">视频上传</label><button type="button" class="layui-btn" id="shipin_src"><i class="layui-icon"> </i>上传视频</button><button type="button" class="layui-btn" id="uploadBtn">开始上传</button><!--缩略预览图--><input type="text" disabled name="src" value="" style="width:300px"> <span id="mv_m"></span><div class="layui-progress layui-progress-big" lay-showPercent="yes" lay-filter="progressBar"><div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div></div></div>(js代码)//上传视频upload.render({elem: '#shipin_src' //绑定元素, url: '/admin/upload/ShiPinUpload' //上传接⼝,accept: 'video',auto:false,bindAction:'#uploadBtn', progress: function(value) {console.log("进度:" + value + '%');element.progress('progressBar',value + '%');},choose: function(obj) {obj.preview(function(index, file, result) {$('input[name="src"]').html();// $('input[name="src"]').val(file.data['src']);});}, done: function (res) {if (res.code>0) {//上传完毕回调layer.msg(res.msg,{icon:2});return false;}else {//上传完毕回调$('#mv_m').html(res.data['sizem']+'M');$('input[name="src"]').val(res.data['src']);layer.msg("上传成功!",{icon:1});}}, error: function () {//请求异常回调}});差点忘记⼀段添加在js之前的代码:(⼀定要添加,这个是检测的上传进度) //创建监听函数var xhrOnProgress = function (fun) {xhrOnProgress.onprogress = fun; //绑定监听//使⽤闭包实现监听绑return function () {//通过$.ajaxSettings.xhr();获得XMLHttpRequest对象var xhr = $.ajaxSettings.xhr();//判断监听函数是否为函数if (typeof xhrOnProgress.onprogress !== 'function')return xhr;//如果有监听函数并且xhr对象⽀持绑定时就把监听函数绑定上去if (xhrOnProgress.onprogress && xhr.upload) {xhr.upload.onprogress = xhrOnProgress.onprogress;}return xhr;}}3.PHP后台接收代码:/*** 视频⽂件上传*** */public function ShiPinUpload(){$file = request()->file('file'); //接收⽂件//判断⽂件是否为空if($file == null){exit(json_encode(['code'=>1,'msg'=>'没有视频上传!']));}//获取上传图⽚⼤⼩$fileImgSize = $file->getInfo('size');$SizeM = $fileImgSize/1048576;//保存⽂件地址$info = $file->move('../public/mv_file');//替换⽂件的路径,输出路径地址$img = str_replace('\\','/','/mv_file'.'/'.$info->getSaveName());exit(json_encode(['code'=>0,'data'=>['src'=>$img,'title'=>$info->getSaveName(),'sizem'=>$SizeM]]));}} ⾮常简单切记⽂件上传功能,⼀定要在php.ini中定义最⼤上传⽂件Size ;如果出现⼤⽂件上传失败:请看下⼀篇⽂章---------。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

这里介绍的文件上传插件为:、例子效果为:官网下载地址:一、参考官网文档,调试出一个最简单的例子,官网文档地址为:/documentation/描述如下:Before implementing an instance of Uploadify, make sure the minimum requirements are met:•jQuery 1.4.x or greater•swfObject 2.2 or greater•Flash Player 9.0.24 or greaterDownload the latest zip package. Extract the following files to a folder named "uploadify" in the root of your website.•cancel.png•jquery.uploadify.v2.1.4.min.js•jquery-1.4.2.min.js•swfobject.js•uploadify.css•uploadify.php•uploadify.swfSave a new page to the root directory of your website and paste the following code into the section:Head Section1.<link href="/uploadify/uploadify.css"type="text/css"rel="stylesheet" />2.<script type="text/javascript"src="/uploadify/jquery-1.4.2.min.js"></script>3.<script type="text/javascript"src="/uploadify/swfobject.js"></script>4.<script type="text/javascript"src="/uploadify/jquery.uploadify.v2.1.4.min.js"></script>5.<script type="text/javascript">6.$(document).ready(function() {7.$('#file_upload').uploadify({8.'uploader' : '/uploadify/uploadify.swf',9.'script' : '/uploadify/uploadify.php',10.'cancelImg' : '/uploadify/cancel.png',11.'folder' : '/uploads',12.'auto' : true13.});14.});15.</script>*Make sure the folder you are uploading to exists and has write permissions.In the body section of the page, add the following code:1.<input id="file_upload"name="file_upload"type="file" />When the page is loaded, the file input will automatically be replaced with the Uploadify file uploader.•We highly recommend using paths that are relative to the root (AKA begin with a /). If this isn't possible, Uploadify does play nice with links that are relative to the page.•Every element that Uploadify is applied to MUST have a unique ID attribute. You can reference elements via class, but each element must have a unique ID.For a more customized uploader, use the options below.说明:以上例子为全英文,调试出的例子如下:16.<link href="<%= path %>/js/uploadify.css" type="text/css" rel="stylesheet" />17.<script type="text/javascript" src="<%= path %>/js/jquery-1.7.js"></script>18.<script type="text/javascript" src="<%= path %>/js/swfobject.js"></script>19.<script type="text/javascript" src="<%= path %>/js/jquery.uploadify.v2.1.4.min.js"></script>20.<script type="text/javascript">21.$(document).ready(function() {22.$('#file_upload').uploadify({23.'uploader' : '<%= path %>/js/uploadify.swf',24.'script' : '<%= path %>/uploadify',25.'cancelImg' : '<%= path %>/cancel.png',26.'folder' : '<%= path %>/upload',27.'auto' : false,28.'fileExt' : '*.rmvb;*.rm;*.png',29.'fileDesc' : '.rmvb,.rm,.PNG',//文件描述,选择文件时,出现在文件类型框中30."buttonText":"upload file", //按钮上的文字可以用图片做按钮,如:buttonImg:"cancel.png"31."height" :20, //选择按钮的高度32."multi":true, //是否允许上传多个文件33."sizeLimit":1024000000,34.'wmode' : 'transparent',//transparent/opaque35."onClearQueue":function(event){36. alert("文件被取消了");37.},38."onComplete":function(){39. alert("上传完成");40.}41.});42.});43.$(function(){44.$("#up").click(function(){45.$("#file_upload").uploadifyUpload();46.});47.$("#cancel").click(function(){48.$("#file_upload").uploadifyClearQueue();49.});50.$("#cancelOne").click(function(){51.$("#file_upload").uploadifyCancel();52.});53.});54.</script>55.</head>56.57.<body>58.This is my JSP page. <br>59.<input id="file_upload" name="file_upload" type="file" /><br>60.<input type="button" value="上传文件" id="up">61.<input type="button" value="取消上传队列" id="cancel">62.<input type="button" value="取消一个上传" id="cancelOne">63.</body>64.</html>二、Uploadify部分参数的介绍:uploader :uploadify.swf 文件的相对路径,该swf文件是一个带有文字BROWSE的按钮,点击后弹出打开文件对话框,默认值:uploadify.swf。

相关文档
最新文档