Response.Redirect a download in progress - asp.net

I have a website where a user can choose to view a video (no copyright) that is on a 3rd party website. From the moment the user choose it, it needs to be downloaded onto my web server before the user can access it. I tried to automatically start the download on the 3rd party website and make a response.redirect with this path, but when the user is watching the video, if the video has only 10 seconds downloaded, any player/browser will considere this video as a ten-seconds video and stop it after 10 seconds.
What would be the best practice to redirect a stream instead of a file?

I found that this piece of code is doing exactly what I want. It downloads a file on a third party website, and as it's streaming it, each chunk is writen in the Response so that it completely obsfuscates the origin. Thus, it is possible to serve any file from any website as if I own it.
Private Sub SendFile(ByVal url As String)
Dim stream As System.IO.Stream = Nothing
Dim bytesToRead As Integer = 10000
Dim buffer() As Byte = New Byte((bytesToRead) - 1) {}
Try
Dim fileReq As System.Net.WebRequest = CType(System.Net.HttpWebRequest.Create(url), System.Net.HttpWebRequest)
Dim fileResp As System.Net.HttpWebResponse = CType(fileReq.GetResponse, System.Net.HttpWebResponse)
If (fileReq.ContentLength > 0) Then
fileResp.ContentLength = fileReq.ContentLength
End If
stream = fileResp.GetResponseStream
Dim resp As System.Web.HttpResponse = HttpContext.Current.Response
resp.ContentType = "application/octet-stream"
resp.AddHeader("Content-Disposition", ("attachment; filename=\""" + ("mp3" + "\""")))
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString)
Dim length As Integer = 1000000
While (length > 0)
If resp.IsClientConnected Then
length = stream.Read(buffer, 0, bytesToRead)
resp.OutputStream.Write(buffer, 0, length)
resp.Flush()
buffer = New Byte((bytesToRead) - 1) {}
Else
length = -1
End If
End While
Catch
stream.Close()
Finally
If (Not (stream) Is Nothing) Then
stream.Close()
End If
End Try
Response.End()
End Sub

Related

VB.NET FTP Picture Upload Error [duplicate]

This question already has answers here:
Zip file is getting corrupted after downloading from server in C#
(3 answers)
Closed 4 years ago.
I am trying to allow authenticated users to upload pictures to the server through FTP. The code works for the most part. The part that doesn't is that there is an issue in uploading the file. I have tried to upload a few different pictures and all of them are larger on the server and therefore, not properly constructed.
One picture I tried is 4.56MB on my computer and 8.24MB on the server. When I load the picture in Photo, it states "We can't open this file." The page location is at http://troop7bhac.com/pages/slideshowedit.aspx. The following is the VB.NET code behind the upload:
Sub uploadFile_Click(sender As Object, e As EventArgs)
lblUploadErrors.InnerHtml = ""
If (lstSlideshowChoose.SelectedValue = "") Then
lblUploadErrors.InnerHtml = "<p>A slideshow must be selected.</p>"
Else
If (FileUpload1.HasFile) Then
Dim nameList() As String
Dim successList() As String
Dim i As Integer = 0
For Each file As HttpPostedFile In FileUpload1.PostedFiles
Dim fileBytes() As Byte = Nothing
Dim fileName As String = Path.GetFileName(file.FileName)
Dim photoRE As New Regex("^[A-z0-9 _]{1,}\.jpg|JPG|jpeg|JPEG|png|PNG+$")
Dim photoSuccess As Boolean = photoRE.Match(fileName).Success
ReDim Preserve nameList(i)
ReDim Preserve successList(i)
If (photoSuccess = True) Then
Using fileStream As New StreamReader(file.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
End Using
Try
Dim request As FtpWebRequest = DirectCast(WebRequest.Create(ftpPath & lstSlideshowChoose.SelectedValue & "/" & fileName), FtpWebRequest)
request.Method = WebRequestMethods.Ftp.UploadFile
request.Credentials = New NetworkCredential(ftpUser, ftpPass)
Using uploadStream As Stream = request.GetRequestStream()
uploadStream.Write(fileBytes, 0, fileBytes.Length)
uploadStream.Close()
End Using
Dim response As FtpWebResponse = DirectCast(request.GetResponse(), FtpWebResponse)
response.Close()
successList(i) = "Success "
Catch ex As Exception
successList(i) = "Failed "
End Try
Else
successList(i) = "Failed "
End If
nameList(i) = fileName
i += 1
Next
For x As Integer = 0 To nameList.Count - 1
lblUploadErrors.InnerHtml += "<p>" & successList(x) & nameList(x) & "</p>"
Next
Else
lblUploadErrors.InnerHtml = "<p>You have not selected a picture to upload.</p>"
End If
End If
End Sub
The files are obtained through an ASP.NET FileUpload control. The control has been set to allow multiple files at once.
Any help to figure out why the pictures are not uploading properly would be greatly appreciated.
EDIT: I tried Martin Prikryl's possible duplicate solution. Had to change it from C# to VB.NET. It failed. I tried David Sdot's solution and it also failed. Both solutions returned the same errors.
If the page was ran on my local machine, it returned "C:\Program Files (x86)\IIS Express\PictureName.JPG." If the page was ran on the server, it returned "C:\Windows\SysWOW64\inetsrv\PictureName.JPG." Both errors are of the System.IO.FileNotFoundException class.
Your Problem is here:
Using fileStream As New StreamReader(file.InputStream)
fileBytes = Encoding.UTF8.GetBytes(fileStream.ReadToEnd())
fileStream.Close()
Using
Your image is read as text. From this text you get the bytes UTF8 byte values, thats why your image is nearly twice the size when uplaoded. You need the bytes from the image, without converting them to something else.
fileBytes = File.ReadAllBytes(file.FileName)

Capture response stream and output to file

We are using an online pdf encoding service where we send them the raw html and they return the pdf document. We want to take the WebResponse and immediately download it as a file to their desktop. This seems so straightforward and yet I can't seem to capture the stream correctly for download. I've tried many different approaches but I always end up with a 0 byte file for download. This is my latest incarnation which has gotten overly complicated but it still doesn't work.
Dim request = DirectCast(HttpWebRequest.Create(Url), HttpWebRequest)
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = byteArray.Length
Using dataStream = request.GetRequestStream()
dataStream.Write(byteArray, 0, byteArray.Length)
End Using
Try
Dim response As WebResponse = request.GetResponse
Dim bytes As Byte()
Using st As Stream = response.GetResponseStream
Dim ByteList As New ArrayList
Dim reader As New BinaryReader(st)
Dim length As Integer
While (InlineAssignHelper(bytes, reader.ReadBytes(1024))).Length > 0
ByteList.Add(bytes)
length += bytes.Length
bytes = New Byte(length - 1) {}
Dim position As Integer = 0
For Each b As Byte() In ByteList
Array.Copy(b, 0, bytes, position, b.Length)
position += b.Length
Next
End While
End Using
HttpContext.Current.Response.Clear()
HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf")
HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Report Detail.pdf; size={1}", "attachment", bytes.Length.ToString()))
HttpContext.Current.Response.BinaryWrite(bytes)
HttpContext.Current.Response.Flush()
HttpContext.Current.Response.Close()
HttpContext.Current.Response.End()
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
target = value
Return value
End Function

Export Crystal Report to PDF in a Loop only works with first

i'm trying to generate a report and export it to pdf in a loop, the report will receive a new parameter in each loop and prompt the client to download a PDF, in other words, the client may need to download 2 or 3 (or more) PDFs at the same time, the problem is that the prompt to accept the download only appears for the first pdf, dont know why. I can export to disk (server side) without any problems.
Code:
Sub PrintReport(ByVal Cod As Integer)
Dim CTableLogInfo As TableLogOnInfo
Dim ConnInfo As CrystalDecisions.Shared.ConnectionInfo = New ConnectionInfo()
ConnInfo.Type = ConnectionInfoType.SQL
ConnInfo.ServerName = ConfigurationManager.AppSettings("SQLSERVERNAME")
ConnInfo.DatabaseName = ConfigurationManager.AppSettings("SQLDBNAME")
ConnInfo.UserID = ConfigurationManager.AppSettings("SQLSERVERUSER")
ConnInfo.Password = ConfigurationManager.AppSettings("SQLSERVERPASSWORD")
ConnInfo.AllowCustomConnection = False
ConnInfo.IntegratedSecurity = False
For Each CTable As Table In CrystalReportSource1.ReportDocument.Database.Tables
CTable.LogOnInfo.ConnectionInfo = ConnInfo
CTableLogInfo = CTable.LogOnInfo
CTableLogInfo.ReportName = CrystalReportSource1.ReportDocument.Name
CTableLogInfo.TableName = CTable.Name
CTable.ApplyLogOnInfo(CTableLogInfo)
Next
Dim pField As ParameterField = CrystalReportSource1.ReportDocument.ParameterFields(0)
Dim val1 As ParameterDiscreteValue = New ParameterDiscreteValue
val1.Value = Cod
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
Dim PDFName As String = "PDF Nº " & Cod
CrystalReportSource1.ReportDocument.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Page.Response, True, PDFName)
End Sub
EDIT:
Tried to zip the reports with DotNetZip but i get an broken zip.
Can you tell me whats wrong? (Solved: code bellow is corrected now)
Response.ClearContent()
Response.ClearHeaders()
Response.ContentType = "application/zip"
Response.AppendHeader("content-disposition", "attachment; filename=AllPDFs.zip")
Using zipFile As New ZipFile()
For i = 0 To Cod.Length - 1
If Cod(i) > 0 Then
val1.Value = Cod(i)
pField.CurrentValues.Clear()
pField.CurrentValues.Add(val1)
val2.Value = Cod(i)
pField2.CurrentValues.Clear()
pField2.CurrentValues.Add(val2)
Dim PDFNameAs String = "PDF Nº " & Cod(i) & ".pdf"
Dim s As New System.IO.MemoryStream
s =CrystalReportSource1.ReportDocument.ExportToStream(ExportFormatType.PortableDocFormat)
zipFile.AddEntry(PDFName, s)
End If
Next
zipFile.Save(Response.OutputStream)
End Using
Response.Clear()
Probably the response ends after the first one, therefore there's no response to write to for the 2nd and 3rd attempts.
Instead, you can have the client download the reports via AJAX Request (move your report generation into an .ashx generic handler), or have the user click the button 3 times to initiate new requests.
Or zip the PDF's up until a single file and allow the client to download that.

First time implementing telerik RadUpload control

I am implementing telerik RadUpload in my asp.net web application.I added corresponding the handler and module entries in web.config.
<add path="Telerik.RadUploadProgressHandler.ashx"
type="Telerik.Web.UI.RadUploadProgressHandler" verb="*" validate="false" />
<add name="RadUploadModule"
type="Telerik.Web.UI.RadUploadHttpModule" />
I have a functionality where I need to upload excel file and need to see the progress bar while uploading until it completes 100%.
PROBLEM: I am wondering how to capture the percentage of file uploaded and show it in progressarea.
MY CODE (Button_Click):
Const total As Integer = 100
Dim progress As RadProgressContext = RadProgressContext.Current
progress.Speed = "N/A"
Dim files As UploadedFileCollection = RadUpload1.UploadedFiles
Dim up As RadUpload = RadUpload1
If files IsNot Nothing AndAlso 0 <> files.Count Then
For i As Integer = 0 To total - 1
progress("SecondaryTotal") = total.ToString()
progress("SecondaryValue") = i.ToString()
progress("SecondaryPercent") = i.ToString()
progress("CurrentOperationText") = files(0).GetName() & " is being processed..."
If Not Response.IsClientConnected Then
Exit For
End If
progress.TimeEstimated = (total - i) * 100
---------ACTUAL UPLOAD FUNCTIONALITY HERE----------
objUpload.CreateBulkUploadRequest(bytes)
Next
End If
Private Sub CreateBulkUploadRequest(bytes)
StoreDocumentinImageServer(bytes)
End Sub
Public Function StoreDocumentinImageServer(ByVal PostData As Byte()) As Integer
Try
Dim req As HttpWebRequest
Dim resp As HttpWebResponse
Dim postStream As Stream
Dim respStream As StreamReader
Dim Url As String
Dim response As String = String.Empty
Dim ImageId As Integer = 0
Dim qryString As New StringBuilder("?fileSize=")
qryString.Append(PostData.Length)
qryString.Append("&userId=" + RequestedBy.ToString)
qryString.Append("&applicationName=" + RequestType.ToString)
qryString.Append("&imageName=" + FileName)
qryString.Append("&mode=Insert")
Url = ImageServiceUrl + qryString.ToString
req = CType(WebRequest.Create(Url), HttpWebRequest)
req.Method = "POST"
req.ContentType = contenttype
req.KeepAlive = True
req.ContentLength = PostData.Length
postStream = req.GetRequestStream()
postStream.Write(PostData, 0, PostData.Length)
resp = CType(req.GetResponse(), HttpWebResponse)
respStream = New StreamReader(resp.GetResponseStream(), Encoding.Default)
response = respStream.ReadToEnd()
respStream.Close()
resp.Close()
Catch ex As Exception
Throw ex
End Try
End Function
PROBLEM---- Now CreateBulkUploadRequest() method is Synchronous , it will take 10 min to upload and finally come out of the method execution. Now mean while how would I update the progress area and percentage of file upload status.
My biggest problem is CreateBulkUploadRequest() is in the loop of progress bar update code.
so it calls as many times it is trying to update the progress area.
AM I DOING CORRECT ????????
Please Let me know If my question is not clear.
Looking forward for any suggestions.
You don't have to handle the display of progress information yourself, it should be done automatically. Have a look at this sample code.
If you are just using the RadUpload and progress area to check the uploaded % then you do not need any additional code in the code-behind. The code (markup) mentioned in this demo should suffice.
However, If you want some custom progress monitoring, which it seems that you are doing with the code provided, you will need to go about this slightly differently. This demo covers just how custom progress monitoring should be implemented. I would double check that the code that you have implemented aligns with the sample in that demo.

FTPWebRequest: Transfer from one FTP to another FTP, Destination file corrupt

Here's my agonizing problem. I'm transferring from one FTP (a Dev site) to another FTP (a Test site). Spare me the thoughts of changing this process. It's out of my hands. In any case, here's my method:
Public Function TransferFile(originalFile As String, destinationFile As String) As String
Try
'FileStream for holding the file
Dim uploadRequest As FtpWebRequest = WebRequest.Create(destinationFile)
uploadRequest.Method = WebRequestMethods.Ftp.UploadFile
uploadRequest.Credentials = New NetworkCredential(ftp_user, ftp_pw)
uploadRequest.UseBinary = True
uploadRequest.UsePassive = False
'connect to the server
Dim fileRequest As FtpWebRequest = WebRequest.Create(originalFile)
fileRequest.Method = WebRequestMethods.Ftp.DownloadFile
fileRequest.Credentials = New NetworkCredential(ftp_user, ftp_pw)
fileRequest.UseBinary = True
fileRequest.UsePassive = False
'get the servers response
Dim response As WebResponse = fileRequest.GetResponse()
'retrieve the response stream
Dim stream As Stream = response.GetResponseStream()
CopyStream(stream, uploadRequest.GetRequestStream)
stream.Close()
response.Close()
Return "File transfered"
Catch ex As System.Security.SecurityException
Return ex.Message
Catch ex As Exception
Return ex.Message
End Try
End Function
Public Shared Sub CopyStream(input As Stream, output As Stream)
Dim buffer As Byte() = New Byte(32767) {}
While True
Dim read As Integer = input.Read(buffer, 0, buffer.Length)
If read <= 0 Then
Return
End If
output.Write(buffer, 0, read)
End While
End Sub
This works perfectly for ASPX files and their .vb code behinds. When we try to transfer .DLL files, they show up on the server as 0 bytes, and sometimes actually transfer. The problem is that, despite being the same size as the original, they act as if they are corrupt. Does anyone have a solution?
Just a guess - use BYREF in your sub definition
Public Shared Sub CopyStream(BYREF input As Stream, BYREF output As Stream)
Closing out the output stream and getting a response from the uploadRequest worked.

Resources