How to Show Progress Bar for Upload with Ftpwebrequest

How can we show progress bar for upload with FtpWebRequest

The easiest is to use BackgroundWorker and put your code into DoWork event handler. And report progress with BackgroundWorker.ReportProgress.

The basic idea:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var ftpWebRequest = (FtpWebRequest)WebRequest.Create("ftp://example.com");
ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
using (var inputStream = File.OpenRead(fileName))
using (var outputStream = ftpWebRequest.GetRequestStream())
{
var buffer = new byte[1024 * 1024];
int totalReadBytesCount = 0;
int readBytesCount;
while ((readBytesCount = inputStream.Read(buffer, 0, buffer.Length)) > 0)
{
outputStream.Write(buffer, 0, readBytesCount);
totalReadBytesCount += readBytesCount;
var progress = totalReadBytesCount * 100.0 / inputStream.Length;
backgroundWorker1.ReportProgress((int)progress);
}
}
}

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar.Value = e.ProgressPercentage;
}

Make sure WorkerReportsProgress is enabled

backgroundWorker2.WorkerReportsProgress = true;

With BackgroundWorker you can also easily implement upload cancellation.

ProgressBar for ftp upload

Untested code, but should give you an idea. Further more I used the using statement:

openFileDialog1.ShowDialog();
FileInfo feltoltfile = new FileInfo(openFileDialog1.FileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpadress + "/" + feltoltfile.Name);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential(textBox1.Text, textBox2.Text);
using (var sourceStream = feltoltfile.OpenRead())
using (var requestStream = request.GetRequestStream())
{
long fileSize = request.ContentLength = feltoltfile.Length;
long bytesTransfered = 0;

byte[] buffer = new byte[4096];
int read;
while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0) //while there are still bytes to be copied
{
requestStream.Write(buffer, 0, read);
requestStream.Flush();
bytesTransfered += read;
//trigger progress event...
}
}
using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
{
serverstatus.Items.Add(response.StatusDescription + " " + feltoltfile.Name + " --> " + DateTime.Now.Hour + ":" + DateTime.Now.Minute + ":" + DateTime.Now.Second);
}
ftplista.Items.Clear();
FTPlistalekerdezes(ftpadress, textBox1.Text, textBox2.Text);
MessageBox.Show("Ready!");

FTP upload ProgressBar in VB.NET

I got this from an example a long time ago. The code should be fairly easy to change for your needs.

Dim clsRequest As System.Net.FtpWebRequest = _
DirectCast(System.Net.WebRequest.Create(ServLabel.Text & TextBox1.Text), System.Net.FtpWebRequest)

clsRequest.Credentials = New System.Net.NetworkCredential(PassLabel.Text, UserLabel.Text)
clsRequest.Method = System.Net.WebRequestMethods.Ftp.UploadFile
rfshTMR.Enabled = True
Dim File() As Byte = System.IO.File.ReadAllBytes(txtFile.Text)
Dim clsStream As System.IO.Stream = _
clsRequest.GetRequestStream()
clsStream.Write(File, 0, File.Length)
For offset As Integer = 0 To File.Length Step 1024
ToolStripProgressBar1.Value = CType(offset * ToolStripProgressBar1.Maximum / File.Length, Integer)
Dim chunkSize As Integer = File.Length - offset - 1
If chunkSize > 1024 Then chunkSize = 1024
clsStream.Write(File, offset, chunkSize)
ToolStripProgressBar1.Value = ToolStripProgressBar1.Maximum
Next
clsStream.Close()
clsStream.Dispose()
MsgBox("File Is Now In Database", MsgBoxStyle.OkOnly, "Upload Complete")

C# FtpWebRequest progress bar tooltip update with uploaded amount

Your code works for me. Assuming you run the uploadFile on a background thread, like:

private void button1_Click(object sender, EventArgs e)
{
Task.Run(() => uploadFile());
}

Sample Image

See also How can we show progress bar for upload with FtpWebRequest

(though you know that link already)


You just update the tooltip too often, so it flickers.

Progress in uploading in ftp server c#

WebClient contains a dedicated event for this

 public event UploadProgressChangedEventHandler UploadProgressChanged 

https://msdn.microsoft.com/en-us/library/system.net.webclient.uploadprogresschanged(v=vs.110).aspx

EDIT : HttpWebRequest approach based on a google result :

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "text/plain";

request.Timeout = -1; //Infinite wait for the response.

// Get the file information object.
FileInfo fileInfo = new FileInfo("C:\\Test\\uploadFile.dat");

// Set the file content length.
request.ContentLength = fileInfo.Length;
// Get the number of segments the file will be uploaded to the stream.
int segments = Convert.ToInt32(fileInfo.Length / (1024 * 4));

// Get the source file stream.
using (FileStream fileStream = fileInfo.OpenRead())
{
// Create 4KB buffer which is file page size.
byte[] tempBuffer = new byte[1024 * 4];
int bytesRead = 0;

// Write the source data to the network stream.
using (Stream requestStream = request.GetRequestStream())
{
// Loop till the file content is read completely.
while ((bytesRead = fileStream.Read(tempBuffer, 0, tempBuffer.Length)) > 0)
{
// Write the 4 KB data in the buffer to the network stream.
requestStream.Write(tempBuffer, 0, bytesRead);

// Update your progress bar here using segment count.
}
}
}
// Post the request and Get the response from the server.
using (WebResponse response = request.GetResponse())
{
// Request is successfully posted to the server.
}

Show progressbar for ftp upload in python

I figured it out. I decided to use TQDM as I found some easier to read documentation for it. I was assuming that storbinary() had to have a return or something to tell it's progress, just didn't know I was looking for a callback.

Anyways I added a new import from tqdm import tqdm

I added this filesize = os.path.getsize(file) to get the file size of the file

Then I replaced ftp.storbinary('STOR ' + FileName, TheFile, 1024) with this code

with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))

And overall the new working code looks like

import os
import ftplib
import ntpath
from tqdm import tqdm

ntpath.basename("a/b/c")

def path_leaf(path):
head, tail = ntpath.split(path)
return tail or ntpath.basename(head)

from glob import glob
FileTransferList = [y for x in os.walk('/tmp/rippedMovies') for y in glob(os.path.join(x[0], '*.mkv'))]

global ftp

def FTP_GLOB_transfer(URL, UserName, Password):
ftp = ftplib.FTP(URL, UserName, Password) # connect to host, default port
print URL, UserName, Password
for file in FileTransferList:
FileName = path_leaf(file)
filesize = os.path.getsize(file)
print file
TheFile = open(file, 'r')
with tqdm(unit = 'blocks', unit_scale = True, leave = False, miniters = 1, desc = 'Uploading......', total = filesize) as tqdm_instance:
ftp.storbinary('STOR ' + FileName, TheFile, 2048, callback = lambda sent: tqdm_instance.update(len(sent)))
TheFile.close()
ftp.quit()
ftp = None

It now outputs as

/tmp/rippedMovies/TestMovie.mkv
Uploading......: 51%|████████████████████▉ | 547M/1.07G
[00:05<00:14, 36.8Mblocks/s]


Related Topics



Leave a reply



Submit