Randomly mapping an image in C# ASP.NET - c#

Quite a bit of looking at this one.
I have an aspx web page with an Image control on it, and I want to load images from my web directory at random to diplay in the image control. The below is the code and how far I have got.
Seems a simple task to request an image file at random and display this in a web page, all I am receiving however is a local filepath (which appears to be no use to the Image Control) and no image on the webpage.
AppSettings.imageUrl returns: "~/Images"
Any suggestions would be appreciated.
protected void Page_Load(object sender, EventArgs e)
{
GetImage();
}
private void GetImage()
{
imgMain.ImageUrl = ResolveClientUrl(RandomImage());
}
private string RandomImage()
{
string mapPath = Request.MapPath(AppSettings.imageUrl);
var rand = new Random();
var files = Directory.GetFiles(mapPath);
return files[rand.Next(files.Length)];

Your RandomImage() method possibly doesn't return file path relative to current page. Either return
string fileName = Path.GetFileName(file[rand.Next(files.Length)]);
return AppSettings.imageUrl + fileName;
and then resolve it or resolve it right away
string fileName = Path.GetFileName(file[rand.Next(files.Length)]);
return Request.MapPath(AppSettings.imageUrl + fileName);

Do a View Source on the resulting page and see if the <img src="..."> is getting set to a sensible value.
On further investigation it seems that ResolveClientUrl takes a relative URL, not an absolute file system path. Therefore RandomImage should return something like:
return AppSettings.imageUrl + "/" + Path.GetFileName(files[rand.Next(files.Length)]);

You're getting the file names. The Directory.GetFiles could also be used in non-web application and therefore it would make no sense to treat the files as relative to your website root.
What you can do is get the local path for root of your site like this:
string root = Request.MapPath("~/");
and then remove that substring from the file you selected:
files[rand.Next(files.Length)].Replace(root, string.Empty);
That's all you need.

Related

FilePicker return name and path as strings

I've got a file Save and file open picker that im now trying to integrate the ability to save the Path and FileName as public variable that will be used across the whole project through different methods etc.
I've currently got a SaveFileClass and OpenFileClass.
I've seen examples of using the OpenFileDialog to return the save directory although I don't believe these are suitable for what im after. Maybe in some shape or form but dont seem to make much sense for the FileOpenPicker and FileSavePicker I have in use currently.
What I have currently (minus the returning directories) is this:
public async Task<IStorageFile> OpenFileAsync()
{
FileOpenPicker openPicker = new FileOpenPicker
{
ViewMode = PickerViewMode.List,
SuggestedStartLocation = PickerLocationId.DocumentsLibrary
};
openPicker.FileTypeFilter.Add(".txt");
openPicker.FileTypeFilter.Add(".csv");
return await openPicker.PickSingleFileAsync();
}
This passes back to the MainPage.
Within here, i would like to have a variable to store the selected file path and the selected file name as a string. These will then be used around the project when it comes to quick saving/auto saving and when building my class to load files.
Im just after whether or not FilePicker has this functionality because my understanding of the documentation is a little limited when trying to integrate it with my scenario.
Your OpenFileAsync method returns a selected IStorageFile and this one has a Name property that gets you the name of the file including the file name extension and a Path property that gets you the full file-system path of the file. You can do whatever you want with these values:
private async void OpenFile_Click(object sender, RoutedEventArgs e)
{
OpenFileClass instance = new OpenFileClass();
IStorageFile file = await instance.OpenFileAsync();
if (file != null)
{
string fileName = file.Name;
string filePath = file.Path;
}
}

while downloading html in pdf,by using third party tool to convert an html page to pdf. getting error- Conversion error: Could not open url

while downloading html code into pdf in selectpdf software. im getting error saying - "Conversion error: Could not open url".im using selectpdf for converting html code to pdf. what is the base url i have to give .
using SelectPdf;
public partial class HtmlcodePrint : System.Web.UI.Page
{
string TxtHtmlCode;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
TxtHtmlCode = #"<html>
<body>
Hello World from selectpdf.com.
</body>
</html>
";
}
}
protected void Btndownloadpdf_Click(object sender, EventArgs e)
{
// read parameters from the webpage
string htmlString = TxtHtmlCode;
string baseUrl = "http://localhost:51868/HtmlcodePrint.aspx";
string pdf_page_size ="A4";
PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
pdf_page_size, true);
string pdf_orientation = "Portrait";
PdfPageOrientation pdfOrientation =
(PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
pdf_orientation, true);
int webPageWidth = 1024;
try
{
webPageWidth = Convert.ToInt32("1024");
}
catch { }
int webPageHeight = 0;
try
{
webPageHeight = Convert.ToInt32("777");
}
catch { }
// instantiate a html to pdf converter object
HtmlToPdf converter = new HtmlToPdf();
// set converter options
converter.Options.PdfPageSize = pageSize;
converter.Options.PdfPageOrientation = pdfOrientation;
converter.Options.WebPageWidth = webPageWidth;
converter.Options.WebPageHeight = webPageHeight;
// create a new pdf document converting an url
PdfDocument doc = converter.ConvertHtmlString(htmlString, baseUrl);
// save pdf document
doc.Save(Response, false, "Sample.pdf");
// close pdf document
doc.Close();
}
}
I know this is old, but I've been working with SelectPdf for a couple of days, so I'll throw in my 2 cents.
You probably don't need a baseUrl...
You don't have to give any baseUrl at all to the ConvertHtmlString function. You can just pass it the html string you want to convert and that's it.
Unless...
You only need to pass it a baseUrl if the html you're converting has relative paths in the external references (example: if you were referencing a stylesheet and wanted to use a relative path, you could provide the baseUrl to show where you wanted the stylesheet to be relative to). It's just so the converter can create the full absolute paths from the relative paths.
So...
If you don't need that functionality or just don't have external references in your html, then you can just use
converter.ConvertHtmlString(htmlString);
Also...
doc.Save(Response, false, "Sample.pdf");
may not be what you're looking for either. I only say this because the comments look like the same ones on the examples on the site for SelectPDF, so I'm assuming you copied the code from there (which is what I originally did too), in which case I want to let you know you don't have to save your PDF doc with that particular version of Save. It actually has 3 overloads to allow you to save your doc as:
a byte array (default)
a stream
a file
an HTTP response (the one you're using now, as shown in the examples from the site)
So, like I pointed out, you're using the one that saves the PDF as a HTTP response, so if you're wanting to save it as an actual PDF file directly, you'll need to change it to
doc.Save(fileName)
with the fileName variable as the absolute or relative path or file name you want to save the PDF to.
Hope this helps

Razor MVC Controller Download file

I have a controller like the code below and I would like to know how to call this using Razor
because #Url.Action("GetFileFromDisk") does not work as expected it just crashes. If it is possible could you point out my mistake here? Or maybe suggest a better way to force on click to download the file
public FilePathResult GetFileFromDisk()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
string fileName = "test.txt";
return File(path + fileName, "text/plain", "test.txt");
}
Thanks in advance.
Update
the Error message I get is
The webpage at http://mypage/Support/GetFileFromDisk might be temporarily down or it may have moved permanently to a new web address.
Error code: ERR_INVALID_RESPONSE`
To force a file download, you should probably use octet-stream. It's up to the client (browser) to determine whether to download or display content, but octet-stream is normally downloaded, no matter what. You should also use Path.Combine instead of manually concatenating the filename with the path.
public FilePathResult GetFileFromDisk()
{
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "uploads/");
string fileName = "test.txt";
return File(Path.Combine(path,fileName), "application/octet-stream", "test.txt");
}
edit, now that you've given the actual error:
This "might be temporarily down" message means no route could be found in your application that matches the given URL. There's probably something wrong with your URL.
Tips:
Check if you can reach actions that are sibling to "GetFileFromDisk" using the same URL pattern.
Review your routes.
Install Glimpse so you can debug your routes.
i think you should be using FileResult if you return File insted of FilePathResult
or use the FilePathResult as return
public FilePathResult GetFileFromDisk()
{
string path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
string fileName = "test.txt";
return new FilePathResult(Path.Combine(path, fileName), System.Net.Mime.MediaTypeNames.Application.Octet);
}

how to display image using imageurl in C#

if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
//string path = Server.MapPath(#"~\\"+Session["parentfolder"].ToString() +"\\"+ Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName);
string root = Server.MapPath("~");
string path = Path.GetDirectoryName(root);
string path1 = Path.GetDirectoryName(path);
string rootfolder = Path.GetDirectoryName(path1);
string imagepath = rootfolder + Session["brandname"].ToString() + "\\" + Seasonfolders.SelectedItem.Text + "\\" + stylefolders.SelectedItem.Text + "\\Images\\" + FileName;
FileUpload1.SaveAs(imagepath);
//objBAL.SaveImage("Image", Session["brandname"].ToString(), Seasonfolders.SelectedItem.Text, stylefolders.SelectedItem.Text, FileName, imagepath, Convert.ToInt32(Session["Empcode"]));
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
}
uploadedimage is ID for Image control. The path of imagepath is E:\Folder1\Folder2\Folder3\Images\1.png
The image is getting saved but I cannot able to display the uploaded image. Do I need to add anything in this line which is to display an image ..
uploadedimage.ImageUrl = Server.MapPath(#"~/"+imagepath);
uploadedimage.DataBind();
Hosting websites or stuff on iis, does not work this way. There are a few concepts one needs to learn on that front, but the best place to start with is understand what is virtual directory.
One quote from the this page:
In IIS 7, each application must have a virtual directory, known as the
root virtual directory, and maps the application to the physical
directory that contains the application's content
So it means this is a directory where the application's "content" reside; it could be simple text files, images, etc, to complex server side pages like aspx or even classic asp, or php, etc. Now anything out of this directory is not accessible by the hosted web application.
Hence the path you intend to share doesn't work that way. There are a few options to handle this scenario.
In iis you could create a sub-virtual directory, and map its path to where your images are stored to the physical location where the images reside.
Provided your web application (when hosted on iis) has access to the path where the images reside, you can write code to read the file, and send the stream of bytes back so that your web page can render image properly.
2nd approach is usually implemented by a handler (ashx) via which you can pass the image name as query string argument, and return the bytes. Hence in short you do something like this:
uploadedImage.ImageUrl = "~/MyImageHandler.ashx?filename=foo.png" //in ur server code.
In the handler you write something like this:
public class MyImageHandler : IHttpHandler {
public void ProcessRequest (HttpContext context) {
// Comment out these lines first:
// context.Response.ContentType = "text/plain";
// context.Response.Write("Hello World");
context.Response.ContentType = "image/png";
var filepath = #"E:\your_image_dir\" + Request.QueryString["filename"];
//Ensure you have permissions else the below line will throw exception.
context.Response.WriteFile(filepath);
}
public bool IsReusable {
get {
return false;
}
}
}
The image Url in your image should be like this
"~/"+ imagepath
Try removing Server.MapPath
Try this
Create Data Folder in your root directory
if (FileUpload1.HasFile)
{
string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
string imagepath =Server.MapPath("~/Data/"+FileName);
FileUpload1.SaveAs(imagepath);
uploadedimage.ImageUrl="~/"+imagepath;
}

File Uploading using Server.MapPath() and FileUpload.SaveAs()

I have a website admin section which I'm busy working on, which has 4 FileUpload controls for specific purposes. I need to know that , when I use the Server.MapPath() Method Within the FileUpload control's SaveAs() methods, Will it still be usable on the web server after I have uploaded the website? As far as I know, SaveAs() requires an absolute path, that's why I map a path with Server.MapPath()
if (fuLogo.HasFile) //My FileUpload Control : Checking if a file has been allocated to the control
{
int counter = 0; //This counter Is used to ensure that no files are overwritten.
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]); // This is the part Im wondering about. Will this still function the way it should on the webserver after upload?
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++; //Here the counter is put into action
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
if (fuLogo.PostedFile.ContentLength > 409600 ) //File must be 400kb or smaller
{
cvValidation.ErrorMessage = "Please use a picture with a size less than 400 kb";
cvValidation.IsValid = false;
}
else
{
if (fuLogo.HasFile && cvValidation.IsValid)
{
fuLogo.SaveAs(logo); //Save the logo if file exists and Validation didn't fail. The path for the logo was created by the Server.MapPath() method.
}
}
}
else
{
logo = "N/A";
}
If you intend to save the files in
a directory on your web server , then
the Server.MapPath() will be the suitable
solution.
string dirPath = System.Web.HttpContext.Current.Server.MapPath("~") + "/Images/Logos/"+ fileBreak[0] + counter.ToString() + "." + fileBreak[1];
Look Here
if you intend to save your files out
the web server then
Use a full path, like "c:\uploads"
and be sure that the web process has
permission to write to that folder,I suggest you store the path itself in the web.config file in this case.
yes, that can be used after saving file and when you try retrieve that file...
Server.MapPath("~/Images/Logos/" + uploadedFileName);
Yes it should still work as Server.MapPath uses the relative values and returns the complete physical path.
It's one line of code:
FileUpload1.PostedFile.SaveAs(Server.MapPath(" ")+"\\YourImageDirectoryOnServer\\"+FileUpload1.FileName);

Categories

Resources