asp.net + previewing an image without saving it locally - asp.net

I a function belows which is being used to preview an image but that involves saving the image locally in my drive. I am using this feature in an data entry form which means if the user discards the form, I have to delete the image which I feel is not efficient. How can I go about previewing the image and only save it locally if the user saves the form. Thanks.
Protected Sub save_btn_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btn_Save.Click
If uifuVouTypeUploadfile.PostedFile IsNot Nothing Then
' Check file size (mustn’t be 0)
Dim myFile As HttpPostedFile = uifuVouTypeUploadfile.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
If nFileLen = 0 Then
'rqfvVouImage.ErrorMessage = "No file was uploaded."
'rqfvVouImage.IsValid = False
Return
End If
' Check file extension (must be JPG)
If System.IO.Path.GetExtension(myFile.FileName).ToLower() <> ".jpg" AndAlso System.IO.Path.GetExtension(myFile.FileName).ToLower() <> ".gif" AndAlso System.IO.Path.GetExtension(myFile.FileName).ToLower() <> ".bmp" Then
'rqfvVouImage.ErrorMessage = "The file must have an extension of JPG or GIF"
'rqfvVouImage.IsValid = False
Return
Else
myFile.SaveAs(MapPath(System.IO.Path.GetFileName(myFile.FileName).ToLower().ToString()))
'Show the uploaded resized picture in the image control
uiimgVouImage.ImageUrl = System.IO.Path.GetFileName(myFile.FileName).ToLower().ToString()
End If
End If
End Sub

You may construct the Bitmap object of uploaded file and write it to Response stream.
Bitmap bmp = new Bitmap(uifuVouTypeUploadfile.PostedFile.InputStream);
bmp.Save(Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
Response.Flush();
Response.End();
Take a look at these posts:
How to show the selected image file without saving file in the disk before upload
Image preview before uploading using AsynFileUpload

Related

How do I generate a thumbnail as I upload a video file using AjaxUploader in Asp.Net/VB.Net?

I am just a beginner so please be gentle. I was given the following code which uploads a video file perfectly. I require it to save a thumbnail at the same time though.. Any ideas?
The 'Save Thumbnail' code below works when uploading an image. It generates a thumbnail perfectly, but not when I upload a video as it's obviously trying to use an image.
Protected Sub AjaxFileUpload1_UploadComplete(sender As Object, e As AjaxControlToolkit.AjaxFileUploadEventArgs) Handles AjaxFileUpload1.UploadComplete
'Save the original image
Dim filename As String = RemoveSpecialChars(e.FileName)
Dim imageFilename As String = DateTime.Now.Ticks.ToString() + "_" + filename
Dim acc As New accounts(Membership.GetUser.ProviderUserKey)
AjaxFileUpload1.SaveAs("E:\kunden\homepages\19\d664110395\www\BargainBoxes\catalog\videos\" & imageFilename)
End Sub
'Save a thumbnail of the image
Dim returnImage As System.Drawing.Image = Image.FromFile("E:\kunden\homepages\19\d664110395\www\BargainBoxes\catalog\videos\" & imageFilename)
Dim thumb As System.Drawing.Image = FixedSize(returnImage, 120, 120)
thumb.Save("E:\kunden\homepages\19\d664110395\www\pool-match-up\catalog\images\thumbnails\" & imageFilename, System.Drawing.Imaging.ImageFormat.Jpeg)
I would like it to show a thumbnail from the first frame of the video.
Many thanks for any advice at all.
Using ffmpeg you can grab a screenshot or many screenshots from a video at any time frame https://ffmpeg.org/download.html
check this to see how https://www.codeproject.com/Articles/24995/FFMPEG-using-ASP-NET in step 2 see "To create thumbnail use the following code.... "

FileUpload file to Azure Blob Storage

I have a System.Web.UI.WebControls.FileUpload control that passes both Word and PDF files that need to be stored in Azure Blob Storage.
From the Code Behind page it passes to the common library to manage Azure Functions:
Private Sub UploadButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UploadButton.Click
Dim fileExt As String = String.Empty
Dim newGuid As New Guid
Dim fileName As String
Dim documentType As Document.DocumentType
Page.Validate()
newGuid = Guid.NewGuid
If Page.IsValid() AndAlso Me.FileUploadNewDoc.HasFile Then
Try
'Test that MIME is either msword of pdf
If FileUploadNewDoc.PostedFile.ContentType.Contains("msword") Then
fileExt = "doc"
documentType = Document.DocumentType.LeaseWordDoc
ElseIf FileUploadNewDoc.PostedFile.ContentType.Contains("pdf") Then
fileExt = "pdf"
documentType = Document.DocumentType.LeasePDF
Else
fileExt = "na"
End If
If fileExt <> "na" Then
fileName = newGuid.ToString & "." & fileExt
AzureStorage.SaveBlob(FileUploadNewDoc.FileContent, fileName, mDocumentContainer, mStorageConnectionString)
End If
Catch ex As Exception
' Handle Error
Finally
FileUploadNewDoc.Dispose()
End Try
End If
End Sub
The AzureStorage.SaveBlob code:
Public Function SaveBlob(ByRef fileContent As Stream,
ByVal fileName As String,
ByVal containerName As String,
ByVal storageConnectionString As String) As Boolean
Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(storageConnectionString)
Dim blobClient As CloudBlobClient = storageAccount.CreateCloudBlobClient()
Dim container As CloudBlobContainer = blobClient.GetContainerReference(containerName)
Dim blockBlob As CloudBlockBlob = container.GetBlockBlobReference(fileName)
Using fileContent
fileContent.Position = 0
blockBlob.UploadFromStream(fileContent)
End Using
Return True
End Function
My questions:
Is this best way to take the File that has been uploaded and save it to Azure Blob Storage?
Am I handling the Stream correctly? I'm passing ByRef and have a Using statement around the usage.
Should I be setting content type explicitly when saving it to storage? If so how do I do that?
Note, I normally code in C# so an example in C# is fine if you're not familiar with VB.NET.
Is this best way to take the File that has been uploaded and save it
to Azure Blog Storage?
The best way depends on your use case. If it is just small files you're OK. If you want to support large files you might want to do chunked uploading. You can take blocks of 1 megabyte which you can upload separately or in parallel. Once you are done uploading all the blocks you commit the file and it is stiched together in Azure Blob storage. Look at CloudBlockBlob.PutBlock and CloudBlockBlob.PutBlockList.
Am I handling the Stream correctly? I'm passing ByRef and have a Using
statement around the usage.
You are but if you want to support larger files you might want to upload with JavaScript and create two endpoint to receive chunks and to commit after all chunks are sent. There are multiple libraries that can help you.
Should I be setting content type explicitly when saving it to storage? If so
how do I do that?
If you upload files that you want to embed in HTML it's wise to have a content type. If you want the links to the file to be download links you don't have to. Although it can never hurt.
blockBlob.Properties.ContentType = "image/jpeg";

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)

Docx File Corrupted after Upload

I have tired many things, searched the internet, and still I cannot figure out what is going on with this code. I still get that my docx files are corrupted, but when I do it with doc file everything is going great.
My Upload Code
Private Sub LbReqUploadAttachment1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles LbReqUploadAttachment1.Click
If FileUplReqAttachment1.HasFile Then
'Then save the attachment to the documents table
Dim type As String = Me.FileUplReqAttachment1.PostedFile.ContentType
Dim myFile As System.Web.HttpPostedFile = Me.FileUplReqAttachment1.PostedFile
Dim nFileLen As Integer = myFile.ContentLength
Dim myData(nFileLen) As Byte
myFile.InputStream.Read(myData, 0, nFileLen)
Dim DocDto As New DocumentsDto
DocDto.Month = Now.ToString("m")
DocDto.Year = Now.Year
DocDto.MimeType = type
DocDto.UploadedById = MyPage.LoggedOnUser.DtoUser.PersonId
DocDto.DocumentBytes = myData.ToArray
DocDto = MyPage.DelegateDocument.CreateDocumentsDto(DocDto)
'Update the order with the new document id
If Me.TbIntlFlagz.Checked Then
Item.AssetID = CStr(DocDto.DocumentID)
Else
Item.AssetID = "0"
End If
' Save Everything
SaveItem()
'Focus after postback
FileUplReqAttachment1.Focus()
End If
'Stay on order screen
Response.Redirect(String.Format("Default.aspx?i={0}&Item={1}", MyPage.DtoPage.PageID, Me.Item.Id))
End Sub
My download code:
Sub ProcessRequest(ByVal context As HttpContext) Implements ttpHandler.ProcessRequest
Dim docba As Byte() = docDto.DocumentBytes
Dim ext As String = Mime.GetExtensionFromMime(docDto.MimeType)
context.Response.ContentType = docDto.MimeType
If String.IsNullOrEmpty(ext) Then
'We can only use the attachment approach if we found a good extension based on the mime type
Else
Dim DispositionHeader As String
If Not context.Request.QueryString.Item("fn") Is Nothing Then
DispositionHeader = String.Format("attachment; filename={0}.{1}", AntiXss.UrlEncode(context.Request.QueryString.Item("fn")), ext)
Else
DispositionHeader = String.Format("attachment; filename={0}.{1}", AntiXss.UrlEncode("Document"), ext)
End If
context.Response.AppendHeader("Content-Disposition", DispositionHeader)
End If
context.Response.Expires = (60 * 24 * 1)
context.Response.OutputStream.Write(docba, 0, docba.Length)
context.Response.Flush()
docba = Nothing
End If
End Sub
I have tired these with no success:
Why are .docx files being corrupted when downloading from an ASP.NET page?
http://www.aspmessageboard.com/showthread.php?230778-Downloaded-docx-files-are-corrupted
https://social.msdn.microsoft.com/Forums/vstudio/en-US/88383fb2-03c6-49f5-afee-ce38497789bd/retrieving-docx-stored-in-sql-server-results-in-there-was-an-error-opening-the-file?forum=vbgeneral
I am uploading the file into a DB, and downloading the file by pressing a hyperlink. When I press the hyperlink and download the file. View at the file it is corrupted.
In VB, when declaring an array you give it the number of elements in the array. This is different from many languages where you specify the last index of the array.
For the code you show, you need to use
Dim myData(nFileLen - 1) As Byte
to make sure that you do not have an extra element in the array.
It appears that the .doc format is not sensitive to this, but .docx is.

Saving Files to user Computer in VB.Net

I have look for days, with no luck.
Can anyone tell me how to save files in VB.Net to any computer? There are lost of articles, but those only tell you about saving to your own computer by giving folder access, not a random user's computer.
You can see my example here http://hanontest.com/POShellCreator.aspx (You have to enter text into task code, project id and notes field, then click create. Then click export, you will see the error.)
I can go to a local Pizza shop website and download a menu pdf, I know its possible.
In my example it saves when you click the button, I would like a save as dialog if anyone knows how to do that as well.
Here is the save string:
Dim regDate As Date = Date.Now()
Dim strDate As String = regDate.ToString(".yyyy\.MM\.dd")
TextBox5.Text = "c:\temp\" & Vendor & "&" & Vendor2 & "&" & Vendor3 & "&" & Vendor4 & TaskEmpty & strDate & ".csv"
Here is how I am saving:
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Define Path to save file.
Dim path As String = TextBox5.Text
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path)
' Add text to the file.
Dim info As Byte() = New UTF8Encoding(True).GetBytes(TextBox3.Text)
fs.Write(info, 0, info.Length)
fs.Close()
End Sub
The error you're seeing there is because you're attempting to save the text file to the server's
file system, which you don't have write access to.
To return a file to user from the server you need to do a little more work, and it's not going to simple on a postback from a button.
You need to send the data down to the client in the Response.OutputStream, instead of your page, and also tell the browser to treat it as a file download:
Response.ContentType = "text/plain";
Response.AppendHeader("Content-Disposition", "attachment; filename=textFile.csv");

Resources