why is the image icon blank/white when fileupload.saveas - asp.net

i use vb.net
i trying to do a file upload, i want to image to save to image folder, however, the image don't know appear in the directory that i indicate
if i click on "show all file", the image appear, but the image icon is blank or white like the image below show
so i click on that image and click on "include it in the project" , however, it shouldnt be the case that i everytime upload an image, i need to redo that again
so how should i allow don't appear the white icon and to always appear in the upload folder when i upload a image instead of manually click on the image to include in ?
this is my code
Protected Sub uploadImage()
Dim filename As String = FileUploadImg.FileName
Dim fileType As String = filename.Substring(filename.Length - 4).ToLower()
If (fileType = ".gif") Or (fileType = ".jpg") Or (fileType = ".png") Then
FileUploadImg.SaveAs("C:\Users\Jane\Desktop\project\FileUpload\FileUpload\WebRole1\images\" & txtboxName.Text & "_" & FileUploadImg.FileName)
Else
MsgBox("failed")
End If
End Sub
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
uploadImage()
'End If
End Sub
this is the image of how it look like

You have to save posted file to persisted storage on the web server and map files to some URL so they can be accessed from the internet.
In Azure environment local disk (like c:) is not persisted (imagine multiple web-roles - how could you serve same image from other instances).
Solution is Azure Blob Storage (you have to set-up it in you Azure Management Console) and upload posted file to the Blob Storage Container.
// Setup the connection to Windows Azure Storage
var storageAccount = CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
var blobClient = storageAccount.CreateCloudBlobClient();
// Get and create the container
var blobContainer = blobClient.GetContainerReference("public-images");
blobContainer.CreateIfNotExist();
// Allow blob to be downloaded
containerPermissions = new BlobContainerPermissions();
containerPermissions.PublicAccess = BlobContainerPublicAccessType.Blob;
blobContainer.SetPermissions(containerPermissions);
// Get the target blob reference
var blobAddressUri = String.Format("{0}{1}", fileName); //create random fileName here
var blob = BlobContainer.GetBlobReference(blobAddressUri);
// Set blob Content-Type
blob.Properties.ContentType = FileUploadImg.PostedFile.ContentType ;
// Upload to the blob storage account
blob.UploadFromStream(FileUploadImg.FileContent);
Your file is now available at blob.Uri.

You have to designate a directory where your uploads will be placed. For example, if I create a new project in C:\, Website1, the direcotry would be C:\Website1. I'd then create a directory under to store uploads: C:\Website1\uploads and make sure to set permissions to read/write for IIS account. I'd then do:
string uploadPath = MapPath( "pictures\\" );
this.fileUpload1.SaveAs( uploadPath + this.fileUpload1.FileName );
Once the file is in the upload directory, I can move it anywhere I like.

Related

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";

Error happens during file open in asp.net on wep page?

I try to open the file and update content in the file, it gets sum error like this.
My code
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)
If Request.QueryString("log") = "no" Then
pinfo.Text = "Invalid Username / Password"
End If
Session.Clear()
Dim FileWriter As StreamWriter
Dim FileReader As StreamReader
Dim Countstr As String
FileReader = File.OpenText("/dmkg/Counter.txt")
Countstr = FileReader.ReadLine
FileReader.Close()
Countstr = Countstr + 700
FileWriter = File.CreateText("/dmkg/Counter.txt")
FileWriter.WriteLine(Countstr)
FileWriter.Close()
End Sub
Check the code and tell me where I am going wrong.
You have to Pass Correct PATH in OpenText Method not File Name
File.OpenText()
Eg:
Dim path As String = "c:\temp\MyTest.txt"
FileReader = File.OpenText(path)
So Make sure your file path is correct.
If it's stored in server then you need to use Server.Mappath()
FileReader = File.OpenText(Server.MapPath("/dmkg/Counter.txt"))
Server.MapPath
To Enable a Access
To grant ASP.NET write access to a path,
right-click the file in Explorer,
choose "Properties" and select the Security tab.
Click "Add" to add the appropriate user or group (typically
{MACHINE}\ASPNET on IIS 5 or Network Service on IIS 6).
Highlight the needed account, and check the boxes for the desired
access.

asp.net + previewing an image without saving it locally

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

FileUpload within a Wizard Control, Processed at the End

This is related to my previous question. An unforeseen issue arose with the Wizard control.
I now know how to upload to FTP, however when using the FileUpload control inside a Wizard control, when you move to the next step, the File you selected gets cleared because of the postback. I need to be able to rename the file according to the results from the Wizard before uploading. So...
I finish my wizard
It uploads some stuff to a database
Renames the file according to those results
Uploads the renamed file to the FTP server
I suspect I will need to follow a procedure something like this, having an upload button next to FileUpload
On "Upload" button click stream the file to the Web Server.
Complete the Wizard.
If the wizard completes successfully, rename file and stream to FTP server.
If the wizard fails, what? Delete the file from the web server? How?
I think I understand the process, so I would like help on how to split my FTP Upload function into two parts with the proper error handling for when the wizard fails.
It would be a great help if you please use the following code as a base. Thanks as always :)
Protected Sub UploadFile(ByVal NewFilename As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
'Function one? - Problem, "NewFilename" depends on the output of the Wizard,
' but obviously it has not been called yet.
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + NewFilename), FtpWebRequest)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
Dim myFileStream As Stream = FileUpload1.FileContent
myFtpWebRequest.ContentLength = myFileStream.Length
'Function two?
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
End Sub
-- ANSWER ---
Here's my final implementation based on input from Icarus :)
For brevity I have excluded the error catching.
'This function is what kicks things off...
Protected Sub UploadFileToWebServer() Handles btnUploadFile.Click
Dim TempDir As String = "C:\TEMP", FileName As String = "uploadedfile.tmp", FilePath As String
If Not Directory.Exists(TempDir) Then
Directory.CreateDirectory(TempDir).Attributes = FileAttributes.Directory
End If
FilePath = TempDir + "\" + FileName
Session.Add("FileName", File1.FileName) 'Keep track of uploaded file name
File1.SaveAs(FilePath)
Session.Add("File", FilePath)
End Sub
After the file is uploaded to the web server, we can continue through the wizard, and when the "Finish" button is clicked, the wizard data gets submitted to the database. The filename is based on the inserted record ID. The following function gets called by the "Final" button click after the record is inserted, and the file finally gets uploaded to the FTP server with the filename changed accordingly.
Protected Sub UploadFileToFtpServer(ByVal FileLinkStr As String)
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
'Defines the filename, path, and upload method, and connection credentials
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + FileLinkStr), FtpWebRequest)
'Be sure to authenticate prior to uploading or nothing will upload and no error
myFtpWebRequest.Credentials = New NetworkCredential(ftpUsername, ftpPassword)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
'Streams the file to the FTP server
'Retrieves File temporarily uploaded to the Web Server during Wizard Processing
Dim iStream As New FileInfo(Session.Item("File"))
Dim myFileStream As Stream = iStream.OpenRead
myFtpWebRequest.ContentLength = myFileStream.Length
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
End Sub
Your understanding is correct. Once you upload the file to the web server (you'd need to place it in a temp directory somewhere and keep track of the file name you gave it) and the wizard completes successfully, you grab that file, rename it accordingly and upload it to the ftp server. If fails, simply call:
File.Delete(Path_to_file_uploaded_on_temp_directory);
You can keep track of the file name given originally, by storing it in Session, for example. When you upload the file to the server initially, do something like Session["FileName"]=Path_to_temp_directory+fileName;
On the final step of the Wizard, get the file name from Session and either rename it and upload it to the FTP Server or delete it.
Of course you need to account for possible name conflicts, etc. You can use a Guid to generate a random name for the file, for example.
I hope I explained this clearly.
EDIT
To make sure I understand correctly...
You need your user to go through all the steps of a Wizard kind of thing
During the process, you ask your user to upload a file.
Because the user has to select a file before the last step of the wizard, you are forced to upload the file immediately the user clicks on the "Next" button to go to the next step of the wizard.
At the very last step of the Wizard, you need to determine whether the file the user has selected should be uploaded to an ftp server (presumably, another box different from your web server) or should be discarded completely.
If the file needs to be uploaded to the FTP server, it needs to be renamed with a special name.
Based on the above, my suggestion is:
When the user clicks "Next" on the step where he selects the file from his computer, you need to save the file immediately to a temporary location on your web server. You save the file to this temporary folder on your web server by doing something like:
if(FileUpload1.HasFile) //user selected a file
{
try
{
//D:\temp is a temp directory on the Web Server
FileUpload1.PostedFile.SaveAs(#"D:\temp\"+FileUpload1.FileName);
//Store the FULL PATH TO the file just uploaded on Session
Session["FileName"]="D:\temp\"+FileUpload1.FileName;
}
catch (Exception ex)
{
//Handle it.
}
}
On the last step of the wizard, assuming everything was successful, do this
Dim myFtpWebRequest As FtpWebRequest
Dim myFtpWebResponse As FtpWebResponse
' You know the NewFileName because it's the output of the wizard
myFtpWebRequest = CType(WebRequest.Create(ftpServer + ftpPath + NewFilename), FtpWebRequest)
myFtpWebRequest.Method = WebRequestMethods.Ftp.UploadFile
myFtpWebRequest.UseBinary = True
'Here you need to read the Original File
Dim myFileStream As Stream = new FileStream(Session["FileName"]),FileMode.Open,FileAccess.Read,FileShare.ReadWrite)
myFtpWebRequest.ContentLength = myFileStream.Length
Dim requestStream As Stream = myFtpWebRequest.GetRequestStream()
myFileStream.CopyTo(requestStream)
requestStream.Close()
myFtpWebResponse = CType(myFtpWebRequest.GetResponse(), FtpWebResponse)
myFtpWebResponse.Close()
If you decide that you should delete the original file uploaded by the user because he did not complete the wizard successfully, you can simply do:
try
{
File.Delete (Session["FileName"]);
}
catch(Exception ex)
{
//Handle it.
}

viewing the images problem

Using ASP.Net and VB.Net
Code
Image1.ImageUrl = "c:\Blue hills.jpg"
The above code is not viewing the image when i clicked the button.
How to solve this problem.
Need Code Help
You shouldn't be referencing the local file path - you should set the ImageUrl to be the URL on the webserver - for example, if you had the file in the root of your website, you'd reference it as:
Image1.ImageUrl = "/Blue%20hills.jpg"
The value you are supplying to the ImageUrl property is a file path and not a Url.
Ideally you should have a folder in your ASP.NET application that holds your image files which you can then reference with either a relative or absolute Url path i.e:
Image1.ImageUrl = "/Content/Images/Blue hills.jpg"
If you want to show pictures from the server disk that are outside of the website root, you have to build "proxy" page. For example call it ShowImage.aspx and it will get the picture name on the URL.
Then you'll have such code
Image1.ImageUrl = "ShowImage.aspx?image=Blue hills.jpg"
And the code for ShowImage.aspx code behind:
string imageName = Request.QueryString["image"] + "";
if (imageName.Length == 0 || imageName.Contains("/") || imageName.Contains("\\") || !imageName.ToLower().EndsWith(".jpg"))
{
throw new Exception("Invalid image requested");
}
else
{
string strFullPath = "C:\\" + imageName;
Response.ContentType = "image/jpeg";
Response.Clear();
Response.WriteFile(strFullPath);
}
Response.End();
This is C# but should be simple enough to translate into VB.NET as well.
Edit: added basic validation that verify that user does not try to fetch files from different directory and allows only .jpg files.
Image1.ImageUrl = System.Web.HttpContext.Current.Server.MapPath("~") + "/"+ "Images" + "/" + "Blue hills.jpg";
but as said before you can't reference a local file like this , except u use HttpHandler.
http://www.15seconds.com/issue/020417.htm

Resources