View image from file in Asp.net - asp.net

In one procedure I correctly create a bmp file called tempimage.bmp. I see the file in the folder, all right.
I would like to see this image in a control of the type System.Web.UI.WebControls.Image, called Image1.
I tried it like this:
string cPath = HttpContext.Current.Server.MapPath(".") + "\\";
Image1.ImageUrl = cPath + "tempimage.bmp";
I don't get any errors but I don't see anything. Where am I wrong?

If D:\DOTNET2019\Sicaweb\ is your root directory
Image1.ImageUrl = "/tempimage.bmp";
If it can change do
Image1.ImageUrl = Page.ResolveUrl("~/tempimage.bmp");

The problem was only the automatic publication of Visual Studio which clears the folder permissions every time.

Related

Image.FromFile "File Not Found" when File is there

I have a file stored in a directory within my site. When I attempt to access the file using image.fromfile, an exception is thrown saying that the file is not there. However, when I access the exact same file using the exact same path but loading it into an image control, the image loads flawlessly verifying that it is there.
The code that throws the file not found exception is:
Private Sub btnCombine_Click(sender As Object, e As EventArgs) Handles btnCombine.Click
Dim BMCanvas As Bitmap 'the "canvas" to draw on
Dim BackgroundTemplate As Image 'the background image
Dim img1Overlay As Bitmap 'the character image
BackgroundTemplate = Image.FromFile("~/Account/Images/Blue 1-02.jpg") 'Template Background Image
img1Overlay = Image.FromStream(FileUpload1.FileContent) 'First overlay image
BMCanvas = New Bitmap(500, 647) 'new canvas
Using g As Graphics = Graphics.FromImage(BMCanvas)
g.DrawImage(BackgroundTemplate, 0, 0, 500, 647) 'Fill the convas with the background image
g.DrawImage(img1Overlay, 50, 50, 100, 100) 'Insert the overlay image onto the background image
End Using
'Setup a path to the destination for the composite image
Dim folderPath As String = Server.MapPath("~/OutFiles/")
'Create a directory to store the composite image if it does not already exist.
If Not Directory.Exists(folderPath) Then
'If Directory (Folder) does not exists Create it.
Directory.CreateDirectory(folderPath)
End If
'Temporarily save the file as jpeg.
BMCanvas.Save(folderPath & "Temp1.jpg", Imaging.ImageFormat.Jpeg)
'View the resulting composite image in image control.
Image1.ImageUrl = folderPath & "Temp1.jpg"
BMCanvas.Dispose()
End Sub
And the code that verifies that the image is in-fact in the directory and successfully displays the image is:
Private Sub cboRole_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboRole.SelectedIndexChanged
If cboRole.SelectedIndex = 1 Then
Image1.ImageUrl = "~/Account/Images/Blue 1-02.jpg"
End If
End Sub
I cannot figure out why one way works and the other way does not.
I have also tried the following code without success:
'Another way to read the image files
Image = File.ReadAllBytes(Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "~/Account/Images/Blue 1-02.jpg")))
OK, the answer to second part of your question (the "Why it's working with ImageUrl?") is located in documentation
Quote:
Use the ImageUrl property to specify the URL of an image to display in
the Image control. You can use a relative or an absolute URL. A
relative URL relates the location of the image to the location of the
Web page without specifying a complete path on the server. The path is
relative to the location of the Web page. This makes it easier to move
the entire site to another directory on the server without updating
the code. An absolute URL provides the complete path, so moving the
site to another directory requires that you update the code.
It (the Image control) already has embedded feature of "Mapping" the path relatively to your web page folder.
When using path from within your code, without controls, like in Image.FromFile, you need to make sure path is correctly mapped, by using Server.MapPath
As you already did in your code for Directory creation.
You cannot have an Image from a relative url.
To get your Image as an System.Drawing.Image you need to get them from a physical path like this (in your case)
Dim image As System.Drawing.Image = System.Drawing.Image.FromFile(HttpContext.Current.Request.PhysicalApplicationPath & "\Account\Images\Blue 1-02.jpg") 'Server.MapPath("~/Account/Images/Blue 1-02.jpg"))

Save file to App_Data folder error

I am trying to save a pdf file generated using Rotativa to the app_data folder of my web app but I get the error :
System.IO.DirectoryNotFoundException: Could not find a part of the path 'E:\www\tsp13amp\website.com\wwwroot\App_Data\Documents\Corps_Profile_userID.pdf'.
My Controller code :
var PDF = new Rotativa.ViewAsPdf("ProfilePrint", model) { FileName = "Corps_Profile_" + User.Identity.GetUserId() + "_" + DateTime.Now.ToString("dd-MM-yyyy")};
var fileName = PDF.FileName;
byte[] pdfBytearray = PDF.BuildPdf(ControllerContext);
var fullPath = Path.Combine(Server.MapPath("~/App_Data/Documents/"),fileName +".pdf");
var byteArray = PDF.BuildPdf(ControllerContext);
System.IO.File.WriteAllBytes(fullPath, byteArray)
What I am trying to do is to store the file in the App_Data folder and a reference to the file in the database which will then be used a link to the file later on like:
Download
Thanks for any help.
Just to make this official - don't store anything in your app_data unless you specifically have a way it will be used. This folder is not mapped by default to return content, as such you'd need an HttpHandler or something specific to serve files from this folder. If you map them to a name in the database you'd still need a way to return them.
You are much better served creating another folder to use for this.

Display image using string builder in ASP.Net

my need is to display an image in a web page using string builder. i know through this snippet sb.Append("<img src=\"bla.jpg\" />"); i can display an image. Here my problem is that the image path is dynamically generated and is in a string variable.
following is the code i tried:
Dim table_builder As New StringBuilder
table_builder.Append("<table width=100%>")
Dim filePath As String = Server.MapPath("../attachments/") & fileName
// file name is the name of the file fetching from the database
table_builder.Append("<tr>")
table_builder.Append("<td>")
table_builder.Append("<img src='" + filePath + "'/>")
table_builder.Append("</td>")
table_builder.Append("</tr>")
But it does not show the image through executing the code
table_builder.Append("</table>")
attach.innerHTML = table_builder.ToString()
Server.MapPath("../attachments/") will map the physical path, that's why the image is not showing. so you can edit your code as:
table_builder.Append("<table width=100%>")
table_builder.Append("<tr>")
table_builder.Append("<td>")
table_builder.Append("<img src='" + "../attachments/" & fileName + "'/>")
table_builder.Append("</td>")
table_builder.Append("</tr>")
table_builder.Append("</table>")
attach.innerHTML = table_builder.ToString()
For your reference ,The Answer by splattne says that :
Server.MapPath specifies the relative or virtual path to map to a physical directory.
Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
Server.MapPath("..") returns the parent directory
Server.MapPath("~") returns the physical path to the root of the application
Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)
Server.MapPath will return the PHYSICAL path of the file on the server. You certainly don't want that as the file will not be accessible from the client side.
You should use relative path
like Dim filePath As String = ("/attachments/") & fileName
with that the file should be accessible from client as
http://domainname.com/attachments/filename
also be careful while using ../ in your paths. You might end up one level lower to your root path and it might not be accessible from client side
Typically ~ can be used to always start the paths from site root

how to load image with relative path in bitmap

i want to upload image int the bitmap object from asp.net, the image is location under
/uploadedimages/sampleimage.jpg
whenever i use below code to load image in bitmap, i gets error saying Parameter not valid.
Bitmap b = new Bitmap("/uploadedimages/sampleimage.jpg") // this path is coming from database holded in variable
i tried to replace the slashes in path to "\" still that does not work.
can anyone tell me what could be the reason for the error and the possible resolution.
Use Server.MapPath. And it's a good practice to use the tilde char ~ to specify the web application root.
Bitmap b = new Bitmap(Server.MapPath("~/uploadedimages/sampleimage.jpg"));
if uploadedimages directory is in your App_Data folder then you should append the App_Data absolute path to your path:
Bitmap b = new Bitmap(Path.Combine(Server.MapPath("~/App_Data"), "/uploadedimages/sampleimage.jpg"));
You can use server.MapPath, pass Url string as given below.
Server.MapPath("../images/image.gif")

storing the files in a web application in asp.net

I have set of components that i wish to let the users download from my web application.
Now the question is where should i place the files in app_data or create a separate folder in asp.net web application as shown here or is there any other optimal solution for this ?
What i mean by components is you can take a look at this ! So what is the best way to do store the components ?
Right now what i'm doing is: i'm storing the files in a external folder outside the application more specifically in documents folder of my c drive, and i'm storing the path to a component as a data element of the table, when ever user clicks on a particular row's button (in the grid view) i'm getting the title of that particular clicked row and querying the database table for the filepath of that component title using these lines of code:
String filePath = dr1[0].ToString(); //GETS THE FILEPATH FROM DATABASE
HttpContext.Current.Response.ContentType = "APPLICATION/OCTET-STREAM";
String disHeader = "Attachment; Filename=\"" + filePath + "\"";
HttpContext.Current.Response.AppendHeader("Content-Disposition", disHeader);
System.IO.FileInfo fileToDownload = new System.IO.FileInfo(filePath);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.WriteFile(fileToDownload.FullName);
Am i doing it properly ? Is there a better/optimal way to do it ?
A user simply needs read access to download a file, so you can simply create a directory claled "Downloads" and place them in there.
You can ensure that people can't "browse" that directory by disabling Directory Browsing and not placing any default docs in there (index.html, default.aspx for example)
What you are currently doing looks like a fairly standard way for providing downloads off your site.
I can't think of something more "optimal".

Resources