上傳文件帶進度條
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顯示進度的