Example #1
0
        public async Task WriteFileAsync(string share, string filename, Stream source, string contentType = "application/octet-stream", CancellationToken token = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(share))
            {
                throw new ArgumentNullException("share");
            }

            if (string.IsNullOrEmpty("filename"))
            {
                throw new ArgumentNullException("filename");
            }

            if (source == null)
            {
                throw new ArgumentNullException("source");
            }

            Exception error = null;
            Stopwatch watch = new Stopwatch();

            watch.Start();
            double time             = watch.Elapsed.TotalMilliseconds;
            long   bytesTransferred = 0;

            IProgress <StorageProgress> progressHandler = new Progress <StorageProgress>(
                progress =>
            {
                bytesTransferred = bytesTransferred < progress.BytesTransferred ? progress.BytesTransferred : bytesTransferred;
                if (watch.Elapsed.TotalMilliseconds > time + 1000.0 && bytesTransferred <= progress.BytesTransferred)
                {
                    OnUploadBytesTransferred?.Invoke(this, new BytesTransferredEventArgs(share, filename, bytesTransferred, source.Length));
                }
            });

            try
            {
                CloudFileShare     choudShare = client.GetShareReference(share);
                CloudFileDirectory dir        = choudShare.GetRootDirectoryReference();
                CloudFile          file       = dir.GetFileReference(filename);
                file.Properties.ContentType = contentType;
                await file.UploadFromStreamAsync(source, source.Length, default(AccessCondition), default(FileRequestOptions), default(OperationContext), progressHandler, token);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is TaskCanceledException)
                {
                    source = null;
                }
                else
                {
                    error = ex;
                    throw ex;
                }
            }
            finally
            {
                watch.Stop();
                OnUploadCompleted?.Invoke(this, new BlobCompleteEventArgs(share, filename, token.IsCancellationRequested, error));
            }
        }
        private void Remote_OnUploadCompleted(object sender, BlobCompleteEventArgs e)
        {
            if (uploadTokenSources.ContainsKey(e.Filename))
            {
                uploadTokenSources.Remove(e.Filename);
            }

            OnUploadCompleted?.Invoke(this, e);
        }
    void SendFileCallback(IAsyncResult result)
    {
        FTContainer.FTSocket.Client.EndSendFile(result);
        FTContainer.FTSocket.Client.Send(encoding.GetBytes("$End"));
        FTContainer.Sending = false;
        DebugLogging("File Uploaded");

        OnUploadCompleted?.Invoke(FTContainer);
    }
Example #4
0
        public async Task WritePageBlobAsync(string containerName, string filename, byte[] source, string contentType = "application/octet-stream", CancellationToken token = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(filename))
            {
                throw new ArgumentNullException("filename");
            }

            if (source == null)
            {
                throw new ArgumentException("source");
            }

            Exception error = null;
            Stopwatch watch = new Stopwatch();

            watch.Start();
            double time             = watch.Elapsed.TotalMilliseconds;
            long   bytesTransferred = 0;

            IProgress <StorageProgress> progressHandler = new Progress <StorageProgress>(
                progress =>
            {
                bytesTransferred = bytesTransferred < progress.BytesTransferred ? progress.BytesTransferred : bytesTransferred;
                if (watch.Elapsed.TotalMilliseconds > time + 1000.0 && bytesTransferred <= progress.BytesTransferred)
                {
                    OnUploadBytesTransferred?.Invoke(this, new BytesTransferredEventArgs(containerName, filename, bytesTransferred, source.Length));
                }
            });

            try
            {
                CloudBlobContainer container = await GetContainerReferenceAsync(containerName);

                CloudPageBlob blob = container.GetPageBlobReference(filename);

                blob.Properties.ContentType = contentType;
                await blob.UploadFromByteArrayAsync(source, 0, source.Length, null, default(AccessCondition), default(BlobRequestOptions), default(OperationContext), progressHandler, token);
            }
            catch (Exception ex)
            {
                if (ex.InnerException is TaskCanceledException)
                {
                    source = null;
                }
                else
                {
                    error = ex;
                    throw ex;
                }
            }
            finally
            {
                watch.Stop();
                OnUploadCompleted?.Invoke(this, new BlobCompleteEventArgs(containerName, filename, token.IsCancellationRequested, error));
            }
        }
Example #5
0
        public async Task <byte[]> ReadFileAsync(string filename, CancellationToken token)
        {
            if (!File.Exists(filename))
            {
                return(null);
            }

            await AccessWaitAsync(filename, TimeSpan.FromSeconds(5));

            readContainer.Add(filename.ToLowerInvariant());

            try
            {
                using (FileStream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
                {
                    byte[] message   = null;
                    int    bytesRead = 0;
                    do
                    {
                        if (token.IsCancellationRequested)
                        {
                            message = null;
                            break;
                        }

                        byte[] buffer = new byte[ushort.MaxValue];
                        bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);

                        if (message == null)
                        {
                            message = new byte[bytesRead];
                            Buffer.BlockCopy(buffer, 0, message, 0, bytesRead);
                        }
                        else
                        {
                            byte[] temp = new byte[message.Length + buffer.Length];
                            Buffer.BlockCopy(message, 0, temp, 0, message.Length);
                            Buffer.BlockCopy(buffer, 0, temp, message.Length, buffer.Length);
                            message = temp;
                        }
                    } while (bytesRead > 0);

                    return(message);
                }
            }
            finally
            {
                readContainer.Remove(filename.ToLowerInvariant());
                if (token.IsCancellationRequested)
                {
                    OnUploadCompleted?.Invoke(this, new BlobCompleteEventArgs(filename, true));
                }
            }
        }
 private void M_ftp2_UploadFileCompleted(object sender, System.Net.UploadFileCompletedEventArgs e)
 {
     try
     {
         OnUploadCompleted?.Invoke(sender, e);
     }
     catch (Exception ex)
     {
         Log.OutputBox(ex);
         Log.ShowError(m_ftp.ErrorMsg);
     }
 }
    void HandOutFileCallback(IAsyncResult result)
    {
        FTSocketContainer ft = (FTSocketContainer)result.AsyncState;

        ft.FTSocket.Client.EndSendFile(result);
        ft.FTSocket.Client.Send(encoding.GetBytes("$End"));
        ft.Sending = false;
        DebugLogging("File Uploaded");

        DequeueUpload(ft);
        OnUploadCompleted?.Invoke(ft);
    }
Example #8
0
        /// <summary>
        /// This method gives you access to the files that were uploaded
        /// </summary>
        /// <param name="eventArgs"></param>
        private async void OnFileChange(InputFileChangeEventArgs eventArgs)
        {
            // Starting the upload
            UploadComplete = false;

            //// Get access to the file
            if (!MultipleFiles)
            {
                await UploadFile(eventArgs.File);
            }
            else
            {
                try
                {
                    // Will upload all the select files
                    IReadOnlyList <IBrowserFile> files = eventArgs.GetMultipleFiles(MaxFileCount);
                    foreach (IBrowserFile file in files)
                    {
                        await UploadFile(file);
                    }
                }
                catch (InvalidOperationException)
                {
                    // If this happens is because the has selected more files than allowed in MaxFileCount
                    UploadedFileInfo uploadedFileInfo = new(null, null, false, null)
                    {
                        // Upload was aborted
                        Aborted      = true,
                        ErrorMessage = FileCountExceededMessage,
                        Exception    = new Exception("The numbers of files to upload is bigger than maximum allowed.")
                    };

                    // Notify the caller the upload was aborted due to an error
                    FileUploaded(uploadedFileInfo);
                }
            }
            // The upload has completed
            UploadComplete = true;

            // Refresh the UI
            StateHasChanged();

            // Fires the event to indicate that all files has been uploaded
            await OnUploadCompleted.InvokeAsync();
        }
Example #9
0
        private async Task UploadAsync(CloudBlockBlob blob, byte[] buffer, CancellationToken token)
        {
            string fullpath = blob.Container.Name + "/" + blob.Name;

            Stopwatch watch = new Stopwatch();

            watch.Start();
            double             time             = watch.Elapsed.TotalMilliseconds;
            long               bytesTransferred = 0;
            BlobRequestOptions options          = new BlobRequestOptions();

            options.SingleBlobUploadThresholdInBytes = 1048576;


            IProgress <StorageProgress> progressHandler = new Progress <StorageProgress>(
                progress =>
            {
                bytesTransferred = bytesTransferred < progress.BytesTransferred ? progress.BytesTransferred : bytesTransferred;
                if (watch.Elapsed.TotalMilliseconds > time + 1000.0 && bytesTransferred <= progress.BytesTransferred)
                {
                    OnUploadBytesTransferred?.Invoke(this, new BytesTransferredEventArgs(fullpath, buffer.Length, progress.BytesTransferred));
                }
            });

            try
            {
                await blob.UploadFromByteArrayAsync(buffer, 0, buffer.Length, default(AccessCondition), options, default(OperationContext), progressHandler, token);
            }
            catch (Exception ex)
            {
                watch.Stop();
                if (ex.InnerException is TaskCanceledException)
                {
                    buffer = null;
                }
                else
                {
                    throw ex;
                }
            }
            OnUploadCompleted?.Invoke(this, new BlobCompleteEventArgs(fullpath, token.IsCancellationRequested));
        }
 private void Operations_OnUploadCompleted(object sender, BlobCompleteEventArgs e)
 {
     OnUploadCompleted?.Invoke(this, e);
 }
Example #11
0
        async void UploadProgress(UploadOperation upload)
        {
            LogStatus(string.Format("Progress: {0}, Status: {1}", upload.Guid, upload.Progress.Status));
            MainPage.Current?.ShowMediaUploadingUc();

            BackgroundUploadProgress progress = upload.Progress;

            double percentSent = 100;

            if (progress.TotalBytesToSend > 0)
            {
                percentSent = progress.BytesSent * 100 / progress.TotalBytesToSend;
            }
            SendNotify(percentSent);
            LogStatus(string.Format(" - Sent bytes: {0} of {1} ({2}%), Received bytes: {3} of {4}",
                                    progress.BytesSent, progress.TotalBytesToSend, percentSent,
                                    progress.BytesReceived, progress.TotalBytesToReceive));

            if (progress.HasRestarted)
            {
                LogStatus(" - Upload restarted");
            }

            if (progress.HasResponseChanged)
            {
                var resp = upload.GetResponseInformation();
                LogStatus(" - Response updated; Header count: " + resp.Headers.Count);
                var          response = upload.GetResultStreamAt(0);
                StreamReader stream   = new StreamReader(response.AsStreamForRead());
                Debug.WriteLine("----------------------------------------Response from upload----------------------------------");

                var st = stream.ReadToEnd();
                Debug.WriteLine(st);
                if (UploadItem.IsVideo)
                {
                    if (!UploadItem.IsStory)
                    {
                        var thumbStream = (await UploadItem.ImageToUpload.OpenAsync(FileAccessMode.Read)).AsStream();
                        var bytes       = await thumbStream.ToByteArray();

                        var img = new InstaImageUpload
                        {
                            ImageBytes = bytes,
                            Uri        = UploadItem.ImageToUpload.Path
                        };
                        await UploadSinglePhoto(img, UploadId);
                    }
                    await Task.Delay(15000);

                    if (!UploadItem.IsStory)
                    {
                        await FinishVideoAsync();
                    }
                    await Task.Delay(1500);
                }
                if (!UploadItem.IsAlbum)
                {
                    await ConfigurMediaAsync();
                }
                else
                {
                    OnUploadCompleted?.Invoke(this);
                }
            }
        }
        /// <summary>
        /// 开始上传
        /// </summary>
        /// <param name="upload"></param>
        public async void UploadStart(Upload upload)
        {
            UploadStatus = UploadStatus.Uploading;
            if (upload != null && upload.FileType != (int)FileType.UNKNOWN)
            {
                using (FileStream fileStream = new FileStream(upload.FilePath, FileMode.Open, FileAccess.Read))
                {
                    var buffer         = new byte[CHUNKSIZE];
                    int chunkNumber    = upload.ChunkNumber;
                    int totalSize      = upload.FileSize;
                    int totalChunks    = (int)Math.Ceiling((double)totalSize / CHUNKSIZE);
                    int bytesRead      = 0;
                    int offset         = chunkNumber * CHUNKSIZE;
                    int uploadedLength = offset;
                    fileStream.Seek((long)offset, SeekOrigin.Begin);

                    while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                    {
                        //如果暂停了
                        if (UploadStatus == UploadStatus.Pause)
                        {
                            break;
                        }
                        //开始时间
                        var watch = new Stopwatch();
                        watch.Start();
                        //byte转换
                        var finalBuffer = new byte[bytesRead];
                        Buffer.BlockCopy(buffer, 0, finalBuffer, 0, bytesRead);
                        //上传一个分片
                        var response = await HttpManager.Instance.BreakPointUploadAsync <BreakPointUploadResponse>(
                            new UploadAlbumFileRequest(upload.TargetId, upload.AlbumId, (AlbumType)upload.AlbumType, upload.FileName, (FileType)upload.FileType, upload.Identifier, totalSize, totalChunks, chunkNumber, CHUNKSIZE, bytesRead), finalBuffer
                            );

                        Logger.Log(response.message);
                        //当前分片上传失败(只要不是完成和分片成功都视为失败)
                        if (!response.Ok && response.code != 201)
                        {
                            OnUploadFailure?.Invoke();
                            break;
                        }
                        //上传完成
                        if (response.Ok)
                        {
                            OnUploadCompleted?.Invoke();
                            UploadManager.DeleteUploader(upload);
                            break;
                        }
                        var progress = Convert.ToDouble((uploadedLength / (Double)totalSize) * 100);
                        //当前分片上传成功
                        upload.Progress    = progress;
                        upload.ChunkNumber = chunkNumber;
                        var a = UploadManager.UpdateUploader(upload);
                        chunkNumber++;//文件块序号+1
                        //结束时间
                        watch.Stop();
                        uploadedLength += bytesRead;
                        //速度计算byte/s
                        var speed = CHUNKSIZE * 1000L / watch.ElapsedMilliseconds;
                        //计算剩余时间
                        var time = (totalSize - uploadedLength) / speed;
                        //上传进度通知
                        OnUploadProgressChanged?.Invoke(progress, (int)time, speed / 1024);
                    }
                }
            }
        }
Example #13
0
        public async Task UploadFileToBlockBlob(string filePath, string containerName, string blobFilename, string contentType = "application/octet-stream", CancellationToken token = default(CancellationToken))
        {
            if (string.IsNullOrEmpty(filePath))
            {
                throw new ArgumentNullException("filenamePath");
            }

            if (string.IsNullOrEmpty(containerName))
            {
                throw new ArgumentNullException("containerName");
            }

            if (string.IsNullOrEmpty("blobFilename"))
            {
                throw new ArgumentNullException("blobFilename");
            }

            if (!File.Exists(filePath))
            {
                throw new FileNotFoundException(filePath);
            }

            Exception error = null;
            Stopwatch watch = new Stopwatch();

            watch.Start();
            double time             = watch.Elapsed.TotalMilliseconds;
            long   bytesTransferred = 0;

            IProgress <StorageProgress> progressHandler = new Progress <StorageProgress>(
                progress =>
            {
                bytesTransferred = bytesTransferred < progress.BytesTransferred ? progress.BytesTransferred : bytesTransferred;
                FileInfo info    = new FileInfo(filePath);
                if (watch.Elapsed.TotalMilliseconds > time + 1000.0 && bytesTransferred <= progress.BytesTransferred)
                {
                    OnUploadBytesTransferred?.Invoke(this, new BytesTransferredEventArgs(containerName, blobFilename, bytesTransferred, info.Length));
                }
            });

            try
            {
                CloudBlobContainer container = await GetContainerReferenceAsync(containerName);

                CloudBlockBlob blob = container.GetBlockBlobReference(blobFilename);
                await blob.UploadFromFileAsync(filePath, default(AccessCondition), default(BlobRequestOptions), default(OperationContext), progressHandler, token);
            }
            catch (Exception ex)
            {
                if (!(ex.InnerException is TaskCanceledException))
                {
                    error = ex;
                    throw ex;
                }
            }
            finally
            {
                watch.Stop();
                OnUploadCompleted?.Invoke(this, new BlobCompleteEventArgs(containerName, blobFilename, token.IsCancellationRequested, error));
            }
        }