当前位置:首页 » 文件管理 » 上传文件带进度条

上传文件带进度条

发布时间: 2022-11-02 11:59:41

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

更多用法可以 参考官网

2. antd vue upload组件使用customRequest上传文件显示文件上传进度

antd-vue上传文件upload组件使用自定义上传方法customRequest无法显示文件上传进度条,如下图红框内的进度条无法显示当前文件上传进度

于是,在网上搜索解决方案:

第一种解决方案是自己封装组件,通过axios请求的onUploadProgress来获取文件上传进度,个人觉得太麻烦;

第二种解决方案是通过upload组件内的方法来显示进度条,参考文章: https://blog.csdn.net/LittleBlackyoyoyo/article/details/104810242

我采用了第二种解决方案,但是使用调用不了参考文章中的`options.onSuccess(res, options.file)` 

于是查看了github上的源码,决定通过$refs调用upload组件中显示进度条的方法和上传成功方法:

html部分:

```html

<a-upload

  ref="uploadRef"

  name="file"

  :multiple="false"

  :showUploadList="true"

  :file-list="fileList"

  :customRequest="customRequest"

  :remove="removeFile"

  @change="fileChange"

>

  <a-button>

  <a-icon type="upload" /> 上传文件</a-button>

</a-upload>

```

js部分:

```javascript

uploadFile('upload_files', fileData.file, {

onUploadProgress: (progressEvent) => {

const percentNum = Math.round((progressEvent.loaded * 100) / progressEvent.total);

this.$refs.uploadRef.onProgress(

{

percent: percentNum

},

fileData.file

)

}

}).then(res => {

fileData.file.status = 'done'

fileData.file.url = this.picsPrefix + res.result

this.$refs.uploadRef.onSuccess(res, fileData.file, '')

})

},

fileChange({ file }) {

if (!file.stop) {

this.fileList = []

this.fileList.push(file)

}

},

```

3. ajax多文件上传如何实现进度条

可以找一个上传插件,如:webupload。
上传插件可以配置显示上传进度,多文件上传可以同时显示多个文件的进度条。
如果自己写的话,需要考虑浏览器兼容和文件上传控制等。

4. 前端上传文件实时显示进度条和上传速度的工作原理是怎样的

后端的责任。

5. JSP 上传文件进度条怎么做

HTTP本身无法实现上传
进度条
,因为无法使用JS访问文件系统,并对
文件流
进行分块。
可以考虑2种方式实现上传进度条:
1.flash:flash可以访问文件系统,并以二进制方式上传文件,这可以将文件进行分块;
2.使用
ActiveX控件
:这个比较复杂一点,能够监控到每一个字节的进度,可以自己开发或使用第三方库。一般来说,对于前台类型的页面,出于安全和可用性不建议使用ActiveX控件,

6. java多文件上传显示进度条

使用 apache fileupload ,spring MVC jquery1.6x , bootstrap 实现一个带进度条的多文件上传,由于fileupload 的局限,暂不能实现每个上传文件都显示进度条,只能实现一个总的进度条,效果如图:

packagecom.controller;

importjava.util.List;

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

importorg.apache.commons.fileupload.FileItemFactory;
importorg.apache.commons.fileupload.ProgressListener;
importorg.apache.commons.fileupload.disk.DiskFileItemFactory;
importorg.apache.commons.fileupload.servlet.ServletFileUpload;
importorg.apache.log4j.Logger;
importorg.springframework.stereotype.Controller;
importorg.springframework.web.bind.annotation.RequestMapping;
importorg.springframework.web.bind.annotation.RequestMethod;
importorg.springframework.web.bind.annotation.ResponseBody;
importorg.springframework.web.servlet.ModelAndView;

@Controller
{
Loggerlog=Logger.getLogger(FileUploadController.class);

/**
*upload上传文件
*@paramrequest
*@paramresponse
*@return
*@throwsException
*/
@RequestMapping(value="/upload.html",method=RequestMethod.POST)
publicModelAndViewupload(HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
finalHttpSessionhs=request.getSession();
ModelAndViewmv=newModelAndView();
booleanisMultipart=ServletFileUpload.isMultipartContent(request);
if(!isMultipart){
returnmv;
}
//Createafactoryfordisk-basedfileitems
FileItemFactoryfactory=newDiskFileItemFactory();

//Createanewfileuploadhandler
ServletFileUploapload=newServletFileUpload(factory);
upload.setProgressListener(newProgressListener(){
publicvoipdate(longpBytesRead,longpContentLength,intpItems){
ProcessInfopri=newProcessInfo();
pri.itemNum=pItems;
pri.readSize=pBytesRead;
pri.totalSize=pContentLength;
pri.show=pBytesRead+"/"+pContentLength+"byte";
pri.rate=Math.round(newFloat(pBytesRead)/newFloat(pContentLength)*100);
hs.setAttribute("proInfo",pri);
}
});
Listitems=upload.parseRequest(request);
//Parsetherequest
//Processtheuploadeditems
//Iteratoriter=items.iterator();
//while(iter.hasNext()){
//FileItemitem=(FileItem)iter.next();
//if(item.isFormField()){
//Stringname=item.getFieldName();
//Stringvalue=item.getString();
//System.out.println("thisiscommonfeild!"+name+"="+value);
//}else{
//System.out.println("thisisfilefeild!");
//StringfieldName=item.getFieldName();
//StringfileName=item.getName();
//StringcontentType=item.getContentType();
//booleanisInMemory=item.isInMemory();
//longsizeInBytes=item.getSize();
//FileuploadedFile=newFile("c://"+fileName);
//item.write(uploadedFile);
//}
//}
returnmv;
}


/**
*process获取进度
*@paramrequest
*@paramresponse
*@return
*@throwsException
*/
@RequestMapping(value="/process.json",method=RequestMethod.GET)
@ResponseBody
publicObjectprocess(HttpServletRequestrequest,
HttpServletResponseresponse)throwsException{
return(ProcessInfo)request.getSession().getAttribute("proInfo");
}

classProcessInfo{
publiclongtotalSize=1;
publiclongreadSize=0;
publicStringshow="";
publicintitemNum=0;
publicintrate=0;
}

}

7. 怎样实现在android实现带进度条的上传效果

实现在android实现带进度条的上传效果效果如图:


用到以下两个类就可实现带进度条的文件上传:


1、CustomMultiPartEntity extends MultipartEntity,


2、HttpMultipartPost extends AsyncTask


代码如下:


import java.io.FilterOutputStream;


import java.io.IOException;


import java.io.OutputStream;


import java.nio.charset.Charset;


import org.apache.http.entity.mime.HttpMultipartMode;


import org.apache.http.entity.mime.MultipartEntity;



public class CustomMultipartEntity extends MultipartEntity {


private final ProgressListener listener;


public CustomMultipartEntity(final ProgressListener listener) {


super();


this.listener = listener;


}


public CustomMultipartEntity(final HttpMultipartMode mode, final ProgressListener listener) {


super(mode);


this.listener = listener;


}


public CustomMultipartEntity(HttpMultipartMode mode, final String boundary,


final Charset charset, final ProgressListener listener) {


super(mode, boundary, charset);


this.listener = listener;


}


@Override


public void writeTo(final OutputStream outstream) throws IOException {


super.writeTo(new CountingOutputStream(outstream, this.listener));


}


public static interface ProgressListener {


void transferred(long num);


}



public static class CountingOutputStream extends FilterOutputStream {


private final ProgressListener listener;


private long transferred;


public CountingOutputStream(final OutputStream out, final ProgressListener listener) {


super(out);


this.listener = listener;


this.transferred = 0;


}


public void write(byte[] b, int off, int len) throws IOException {


out.write(b, off, len);


this.transferred += len;


this.listener.transferred(this.transferred);


}


public void write(int b) throws IOException {


out.write(b);


this.transferred++;


this.listener.transferred(this.transferred);


}


}


}


该类计算写入的字节数,我们需要在实现ProgressListener中的trasnfered()方法,更行进度条



public class HttpMultipartPost extends AsyncTask<HttpResponse, Integer, TypeUploadImage> {



ProgressDialogpd;



longtotalSize;



@Override


protectedvoidonPreExecute(){


pd= newProgressDialog(this);


pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);


pd.setMessage("Uploading Picture...");


pd.setCancelable(false);


pd.show();


}



@Override


(HttpResponse... arg0) {


HttpClienthttpClient = newDefaultHttpClient();


HttpContexthttpContext = newBasicHttpContext();


HttpPosthttpPost = newHttpPost("http://herpderp.com/UploadImage.php");



try{


= newCustomMultipartEntity(


newProgressListener() {



@Override


public void transferred(longnum){


publishProgress((int) ((num / (float) totalSize) * 100));


}


});



// We use FileBody to transfer an image


multipartContent.addPart("uploaded_file", newFileBody(


newFile(m_userSelectedImagePath)));


totalSize= multipartContent.getContentLength();



// Send it


httpPost.setEntity(multipartContent);


HttpResponseresponse = httpClient.execute(httpPost, httpContext);


String serverResponse = EntityUtils.toString(response.getEntity());



ResponseFactoryrp = newResponseFactory(serverResponse);


return(TypeImage) rp.getData();


}



catch(Exception e) {


System.out.println(e);


}


returnnull;


}



@Override


protectedvoidonProgressUpdate(Integer... progress){


pd.setProgress((int) (progress[0]));


}



@Override


protectedvoidonPostExecute(TypeUploadImageui) {


pd.dismiss();


}


}

在 transferred()函数中调用publishProgress((int) ((num / (float) totalSize) * 100));


在onProgressUpdate()实现上传进度的更新操作

8. 大神,ThinkPHP 上传文件进度条怎么实现的

Web Uploader
这个插件是网络出的,有进度条,兼容ie7及以上。
原理就是ajax上传,会返回1-100的数值,根据这个值来操作进度条。如果还有不明白的话,你可以在后盾人看看视频找找答案,有空多看看时间长了,慢慢就明白了,希望能帮到你,给个采纳吧谢谢

9. JSP 上传文件进度条怎么做

使用第三方开源的吧:比如jquery的uploadify插件就可以,唯一缺点就是它是用flash显示进度的

热点内容
byte转intjava 发布:2024-06-29 23:14:22 浏览:103
安卓手机网页版怎么用 发布:2024-06-29 23:09:33 浏览:124
如何给安卓下音乐 发布:2024-06-29 23:08:45 浏览:61
对峙二服务器为什么总是丢失 发布:2024-06-29 22:52:56 浏览:582
javaaes文件加密 发布:2024-06-29 22:48:09 浏览:967
android应用名称修改 发布:2024-06-29 22:27:18 浏览:271
怎么让安卓限制下载 发布:2024-06-29 22:27:11 浏览:206
我的世界服务器怎么开pvp 发布:2024-06-29 22:24:48 浏览:115
哪些手机配置麒麟980 发布:2024-06-29 21:57:42 浏览:903
我的世界服务器新手引导 发布:2024-06-29 21:27:45 浏览:160