上傳進度條代碼
⑴ 怎樣實現在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()實現上傳進度的更新操作
⑵ asp 如何實現帶進度條的上傳文件功能
以下就以abcupload4為例來說明怎麼來製作實時的文件上傳進度條。
(註:我們在abcupload自帶例子基礎上改進。)
progressupload.htm(上傳文件的前台提交,我們讓進度條在這個裡面顯示)
<HTML>
<body>
<script language="javascript">
<!--
theUniqueID = (new Date()).getTime() % 1000000000;
function s() //讓數據提交的同時執行顯示進度條的函數
{
bar(); //開始執行反映上傳情況的函數
document.myform.action = "progressupload.ASP?ID=" theUniqueID; //處理上傳數據的程序
document.myform.target="up" //將提交的數據放在一個名字是up隱藏的iframe裡面處理,這樣提交的頁面就不會跳轉到處理數據的頁
document.myform.submit(); //提交表單
}
function bar()
{
bar1.style.display=''; //讓顯示上傳進度顯示的層的可見
var timeoutid=null; //這個變數是作定時器的ID
var oXMLDoc = new ActiveXObject('MSXML'); //創建'MSXML'對象
sURL = "progressbar.ASP?ID=" theUniqueID "&temp=" Math.random(); //獲取上傳狀態數據的地址
oXMLDoc.url = sURL; //load數據
var oRoot=oXMLDoc.root; //獲取返回XML數據的根節點
if(oRoot.children != null)
{
if (oRoot.children.item(0).text-100==0) //文件上傳結束就取消定時器
clearTimeout(timeoutid)
PercentDone.style.width=oRoot.children.item(0).text "%"; //設置進度條的百分比例
//根據返回的數據在客戶端顯示
min.innerHTML=oRoot.children.item(1).text; //顯示剩餘時間(分鍾)
secs.innerHTML=oRoot.children.item(2).text; //顯示剩餘時間(秒鍾)
BytesDone.innerHTML=oRoot.children.item(3).text; //已上傳數據大小
BytesTotal.innerHTML=oRoot.children.item(4).text; //總大小
BytesPerSecond.innerHTML=oRoot.children.item(5).text; //傳輸速率
Information.innerHTML=oRoot.children.item(6).text; //上傳信息
}
if (oRoot.children.item(0).text-100<0) //只要文件沒有傳完,就每隔多少時間獲取一次數據
timeoutid = setTimeout("bar()",50) //這里設定時間間隔是0.05秒,你也可以根據你的情況修改獲取數據時間間隔
}
//-->
</script>
<form name="myform" method="post" action="progressupload.ASP" enctype="multipart/form-data" target=up>
<input type="file" name="filefield1"><br>
<input type="button" name="dosubmit" value="Upload" onclick="s()"><br>
<div id=bar1 style="display:none">
<table border="0" width="100%">
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="2"><b>傳送:</b></font></td>
</tr>
<tr bgcolor="#999999">
<td>
<table border="0" width="" cellspacing="1" bgcolor="#0033FF" id=PercentDone>
<tr>
<td><font size=1></font></td>
</tr>
</table>
</td>
</tr>
<tr>
<td>
<table border="0" width="100%">
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">剩餘時間:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">
<span id=min></span> 分
<span id=secs></span> 秒
(<span id=BytesDone></span> KB of
<span id=BytesTotal></span> KB 已上傳)</font></td>
</tr>
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">
傳送速度:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">
<span id=BytesPerSecond></span> KB/秒</font></td>
</tr>
<tr>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1">信息:</font></td>
<td><font face="Verdana, Arial, Helvetica, sans-serif" size="1"><span id=Information></span></font></td>
</tr>
</table>
</td>
</tr>
<tr></tr>
</table>
</div>
<iframe name="up" style="display:none"></iframe>
</form>
</body>
</HTML>
progressbar.ASP(返回上傳狀況數據的文件)
<%@EnableSessionState=False%>
<%
On Error Resume Next
Set theProgress = Server.CreateObject("ABCUpload4.XProgress") '創建上傳組件對象
theProgress.ID = Request.QueryString("ID")
'將返回數據以XML格式輸出
%>
<?XML version="1.0" encoding="gb2312" ?>
<plan>
<PercentDone><%=theProgress.PercentDone%></PercentDone>
<min><%=Int(theProgress.SecondsLeft/60)%></min>
<secs><%=theProgress.SecondsLeft Mod 60%></secs>
<BytesDone><%=Round(theProgress.BytesDone / 1024, 1)%></BytesDone>
<BytesTotal><%=Round(theProgress.BytesTotal / 1024, 1)%></BytesTotal>
<BytesPerSecond><%=Round(theProgress.BytesPerSecond/1024, 1)%></BytesPerSecond>
<Information><%=theProgress.Note%></Information>
</plan>
progressupload.ASP(處理上傳文件)
<%@EnableSessionState=False%>
<%
Response.Expires = -10000
Server.ScriptTimeOut = 300
Set theForm = Server.CreateObject("ABCUpload4.XForm")
theForm.Overwrite = True
theForm.MaxUploadSize = 8000000
theForm.ID = Request.QueryString("ID")
Set theField = theForm("filefield1")(1)
If theField.FileExists Then
theField.Save theField.FileName
End If
%>
<HTML>
<body>
傳送結束
</body>
</HTML>
⑶ c#中,上傳文件需要進度條,應該怎樣使用
c#有一個progressBar控制項就是進度條,開線程,線程函數中加循環,循環執行progressBar1.Value=(int)((已上傳大小/總大小)*100)來顯示當前進度。
⑷ 使用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)]
更多用法可以 參考官網