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
Related
I'm beginner in asp.net and want to write simple web application to end user can download any file,write this code for that purpose:
string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);
if (file.Exists) {
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment; filename=" + query[0].OstFileName.Trim());
Response.TransmitFile(Server.MapPath("~/beh/" + query[0].OstFileName.Trim()));
Response.End();
} else {
Response.Write("<script>alert('File Not Found 1')</script>");
}
but when run that code i get else block alert,means get File Not Found 1 message,Where is my fault?thanks all.
string filePath = "~/beh/" + query[0].OstFileName;
In this line you specify the path to search for, including the filename.
The next line you check if this file exists and if so save the file from the query result.
However if you check if the file exists before you actually save the file it will never exist.
Change the path to read: string filePath = Server.MapPath("~\beh").
Then add the filename to that once you save the file.
Hope this makes sense.
Your issue is in the following lines.
string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file = new FileInfo(filePath);
You're giving the FileInfo class a virtual path which the FileInfo cannot map to a local physical path on its own. You are however correctly mapping the virtual path to the local file path when you call Response.TransmitFile.
Change your code to the following:
string filePath = "~/beh/" + query[0].OstFileName;
FileInfo file - new FileInfo(Server.MapPath(filePath));
See: https://msdn.microsoft.com/en-us/library/ms524632(v=vs.90).aspx
Earlier developer had put this code using a label and it was turned into a hyperlink during the run time.
<asp:Label ID="lbl_Attachment" runat="server">
</asp:Label>
lbl_Attachment.Text = "<a href='../Uploads/" +
ds_row["Attachment"].ToString() + "'>" +
ds_row["Attachment"].ToString() + "</a>";
But this is not working. So I changed the code to the following to open the any file (image/pdf/word) in a new browser tab and the error persists:
hyperlinkAppDoc.NavigateUrl =
ResolveUrl("../Uploads/" +
ds_row["Attachment"].ToString());
hyperlinkAppDoc.Target = "_blank";
What can I do to fix this issue? MIME types are available in the IIS.
UPDATE:
I am trying out a different approach. However the Server.MapPath is poiting at local drive instead of wwwroot. How can I point the path to wwwroot folder?
string pdfPath = Server.MapPath("~/SomeFile.pdf");
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(pdfPath);
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
You could have used asp.hyperlink. Like following
<asp:HyperLink id="hyperlink1" NavigateUrl="<set_from_code_behind>" Text="Text to redirect" runat="server"/>
And set NavigateUrl from code behind as following.
hyperlink1.NavigateUrl= "Uploads/" + ds_row["Attachment"].ToString();
In your situation, I suggest you to add one key in <appSettings> tag in your web config file.
<appSettings>
<add key="WebsiteURL" value="http://localhost:1234/WebsiteName/"/>
</appSettings>
Next step is to take one hyperlink in your .Aspx file.
<asp:HyperLink ID="HyperLink1" runat="server" Target="_blank"></asp:HyperLink>
In code behind concatenate AppSettings Key + Download file path from root.
string base_path = ConfigurationSettings.AppSettings["WebsiteURL"];
HyperLink1.NavigateUrl = base_path + "Uploads/" + ds_row["Attachment"].ToString();
Please let me know if you have any questions.
All the sweat was due to path issue. Old code and new code works. There's no need for a web client code.
The upload path was set here:
public static string UploadDirectory = ConfigurationManager.AppSettings["UploadDirectory"];
It was pointing to a different directory in the root other than where the application was. Therefore the files were only uploaded but never picked up.
I changed it to AppDomain.CurrentDomain.BaseDirectory for now. After we talk with the users, we will set it accordingly.
I am getting the content of Image in byteArray format from the database and displaying it in the Content image tag in ASP.NET.The problem is that when I save the image file in a specific location in my working folder and display the image,it is working fine.But if I try to save the image in a temporary folder and pass the temporary folder URL to image tag it doesn't display the image.
code:
Bitmap bi = new Bitmap(byteArrayToImage(FileUpload1.FileBytes));
//This code working fine
string path = Server.MapPath("Images/") + FileUpload1.PostedFile.FileName;
bi.Save(path , ImageFormat.Jpeg);
Image1.ImageUrl = "Images/" + FileUpload1.PostedFile.FileName;
//This code didn't displaying the image.
bi.Save(Path.GetTempPath() + FileUpload1.PostedFile.FileName, ImageFormat.Jpeg);
Image1.ImageUrl = Path.GetTempPath() + FileUpload1.PostedFile.FileName;
what is the problem with the tempFolder here?.I am using the Windows7 OS.Here i am using the temparory folder for automatically deleting the created images from the folder.
Thank you
Did you debug and check if the ImageUrl is correct
Images not displaying in adrotator where its picture path like "C:\Uploader\Image.jpg" or some shared folder in server.If i give the path inside my project,its working but outside the project ( like "C:\Uploader\Image.jpg") it not showing anything.
<telerik:RadRotator ID="radSlider" runat="server" FrameDuration="400" ScrollDuration="500"
ScrollDirection="Left" Height="250px" Width="550px">
<ItemTemplate>
<img src='<%# Eval("FullName") %>' alt="Friday" width="550px" />
</ItemTemplate>
</telerik:RadRotator>
Here i am attaching the path dynamically using databind.What is the problem.Plz help me?Telerik or asp control
The client browser will never know where those images are unless you map a virtual directory to the images. Even you can not use Server.MapPath() etc to map the drive.
You should use an HttpHandler to access the file outside of your
application virtual directory.
Check following SO thread that much relevant to your problem:
Show Images from outside of ASP.NET Application
Another approach that i have gotten after goggle about this as follow:
You can try to access the file outside application's virtual directory. you need to pay attention to the folder/file enough permission.
you can to access the images in your website, you can check the following link:
Displaying images that are stored outside the Website Root Folder
protected void Page_Load(object sender, EventArgs e)
{
if (Request.QueryString["FileName"] != null)
{
try
{
// Read the file and convert it to Byte Array
string filePath = "C:\\images\\";
string filename = Request.QueryString["FileName"];
string contenttype = "image/" +
Path.GetExtension(Request.QueryString["FileName"].Replace(".","");
FileStream fs = new FileStream(filePath + filename,
FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
//Write the file to response Stream
Response.Buffer = true;
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = contenttype;
Response.AddHeader("content-disposition", "attachment;filename=" + filename);
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
catch
{
}
}
}
Hope this help.
You should use IHttpHandler to serve your files in a different location (e.g. outside of application root or in privileged folders). AFAIK, Telerik Rad Controls has a RadBinaryImage or something for such usages.
Is it possible to upload a file directly into an ftp account folder with ASP.NET ?
E.g. I click on browse, select a file to upload and when I click "upload" button, It should save it directly to the folder on another web server located at somewhere else other then the server that is being used to upload.
As I understand your question, you want to upload the file to another remote server (so it's not another server sitting on the same network as your web server)? In that case you can do a couple of different things. The easiest way is perhaps to start by making a regular file upload you your server, and then have your server send the file via FTP to the other remote server:
string fileName = Path.Combine("<path on your server", FileUpload1.FileName);
FileUpload1.SaveAs(fileName);
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.UploadFile(
New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName),
localFile);
}
...or it might work doing it in one step:
using(System.Net.WebClient webClient = new System.Net.WebClient())
{
webClient.UploadData(
New Uri("ftp://remoteserver/remotepath/" + FileUpload1.FileName),
FileUpload1.FileBytes);
}
(I din't try this code out, so there could be some errors in it...)
Update: I noticed that I was wrong in assuming that the UploadXXX methods of WebClient were static...
You can use the WebClient class to store the uploaded file to FTP (without saving it as a file on the server). Something like this:
string name = Path.GetFileName(UploadControl.FileName);
byte[] data = UploadControl.FileBytes;
using (WebClient client = new WebClient()) {
client.UploadData("ftp://my.ftp.server.com/myfolder/" + name, data);
}
/// <summary>
/// Example call : if (FtpUpload(FileUploadControl1, "ftp.my.com/somePathDir", #"user", "pass!", "domain"))
/// </summary>
/// <param name="file"></param>
/// <param name="ftpServer"></param>
/// <param name="username"></param>
/// <param name="ftpPass"></param>
/// <returns></returns>
private bool FtpUpload(FileUpload file, string ftpServer, string username, string ftpPass, string domainName = "")
{
// ftp://domain\user:password#ftpserver/url-path
// If you are a member of a domain, then "ftp://domain-name\username:password#url-path" may fail because the backslash (\) is sent in as a literal character and Internet Explorer incorrectly looks for a file instead of parsing a Web address. Changing the backslash (\) in the domain-name\username to domainname%5Cusername works correctly.
try
{
string ftpAddres;
if (domainName != string.Empty)
ftpAddres = "ftp://" + domainName + #"%5C" + username + ":" + ftpPass + "#" + ftpServer + "/" + file.FileName;
else
ftpAddres = "ftp://" + username + ":" + ftpPass + "#" + ftpServer + "/" + file.FileName;
using (var webClient = new System.Net.WebClient())
{
webClient.UploadData(new Uri(ftpAddres), file.FileBytes);
}
}
catch (Exception e)
{
throw new Exception(e.Message, e);
}
return true;
}
You cannot upload it to an FTP directly from your HTML form. However, you can upload it to your ASP.NET application and then upload it to the FTP from there using FtpWebRequest.
EDIT
First off the # sign is there to flag the string as a literal. it saves you having to escape characters like backslashes. e.g.
string path = "Z:\\Path\\To\\File.txt";
string path = #"Z:\Path\To\File.txt";
Secondly, if you only have FTP Access to the other server, then you can take, the FileUpload.FileBytes Property of the FileUpload control. That will give you a byte[] of the file contents.
From this you use the System.Net.FtpWebRequest & System.Net.FtpWebResponse to upload your file to the FTP Account.
Theres some sample code here in VB.NET but it should be easy enough for you to figure out
http://www.programmingforums.org/thread15954.html
ORIG
The file upload control will provide you with the File on your webserver.
It would be up to you, to copy/save that file then from the webserver to whatever server
you're FTP is hosted on.
Do you have a UNC Path/Mapped Drive shared out on your other server that you can save to.
The FileUpload Control has a .SaveAs() method so it's just a simple matter of
if (FileUpload1.HasFile)
try
{
FileUpload1.SaveAs(#"Z:\Path\On\Other\Server\" + FileUpload1.FileName);
}