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);
Related
I'm developing an HTML editor in C# where you can edit your code in the FastColoredTextBox.dll component. You will have this option in the MenuStrip called "Preview in browser" and there will be a drop down item called "Chrome" and "Iexplore" etc. I want it instead of saving the file, i want it to make a file in the Temp folder and preview it. and after we've modified the code again, the file will update as we preview it again. This is what i have so far:
string location = null;
string sourcecode = FastColoredTextBox1.Text;
location = System.IO.Path.GetTempPath() + "\\TempSite.html";
using (StreamWriter writer = new StreamWriter(location, true))
{
writer.Write(sourcecode);
writer.Dispose();
}
try
{
System.Diagnostics.Process.Start("chrome.exe", location);
}
catch (Exception ex)
{
Interaction.MsgBox(ex.Message);
}
How do you achieve this?
Q: How do you save and preview an HTML file from temp folder?
A: You're already doing precisely that :)
Q: Why does my browser keep re-displaying the original image?
A: Because your browser is reading the html from cache.
SOLUTION:
Give your new file a different name. For example:
location = System.IO.Path.GetTempPath() + Path.GetTempFileName() + ".html";
... OR ...
location = Path.GetTempPath() + Guid.NewGuid().ToString() + ".html";
You can also simply hit <F5> to refresh, <Ctl-Shift-Del> to clear cache, or disable cache in your browser.
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;
}
In the below code i have a image i have pass image url from codebehind but it is not displaying the image.
The url location is C:\Search\Searchdoc\Documents\Desert.jpeg
public string strClientName = "Searchdoc";
public string strDocumentFolder = "Documents";
string Imgdocname = SearchDoc.DocumentName;
string fileExt = System.IO.Path.GetExtension(Imgdocname);
fileExt = fileExt.ToLower();
if (fileExt == ".jpeg" || fileExt == ".jpg")
{
docimg.Src = "~/" + Search+ "/" + strClientName + "/" + strDocumentFolder + "/" + Imgdocname;
docimg.Visible = true;
}
else
{
docimg.Src= "~/Search/Searchdoc/Documents/image.jpeg";
docimg.Visible = true;
}
Well for a start, you are using the ~ character which indicates the root directory of the application.
Since you are saying that the image is in C:\Search\Searchdoc\Documents\ then that won't be found, since your code is actually looking in projectRoot\Search\Searchdoc\Documents
As for how to get this image to show in a webpage, it won't simply work for accessing it from the C drive. IIS will not serve images that aren't in the web site folder structure. I would suggest moving it into the website.
If you need to keep it stored in a folder outside your website, you would need to look at streaming it, or using a sort of proxy page. Have a look at the answer here: How to display image which is stored in local drive? to get an idea of the proxy method
I have a project ASP MVC.In my project i have a form for upload image i used
string path = System.IO.Path.Combine(Server.MapPath("~/images/"));
if (Request.Files.Count > 0 && Request.Files[0].ContentLength > 0)
{
string url = path + home.Image;
if (System.IO.File.Exists(path + home.Image))
{
System.IO.File.Delete(path+home.Image);
}
FileInfo FInfo = new FileInfo(Request.Files[0].FileName);
string filename = "sample";
string ImagePath = path;
Request.Files[0].SaveAs(ImagePath + filename + FInfo.Extension);
}
Above this code in my local system perfectly .I hosted my project in my site.But it now working in my site.
Any one know please help me
Thanks
Please check your path for image folder,
Please check that you have write permission on folder in which you uploading image,
If you do not have permission then go to security tab and allow full control to everyone,
how to filter the file type with the file upload control in asp.net & c#.net
for example on clicking the browse button of the file upload control ,it should open browse file dialog with only excel file types.
how is it possible
It works perfectly!
<asp:FileUpload ID="FileUpload1" runat="server" accept=".xls, .xlsx"/>
this is the answer from the other forum
I think it 's easy to realise it if you use C# (or VB,net) and .net fileupload control. you may define file types in arraylist "allowedExtensions".
string upload_Image(FileUpload fileupload, string ImageSavedPath)
{
FileUpload fu = fileupload;
string imagepath = "";
if (fileupload.HasFile)
{
string filepath = Server.MapPath(ImageSavedPath);
String fileExtension = System.IO.Path.GetExtension(fu.FileName).ToLower();
String[] allowedExtensions = { ".gif", ".png", ".jpeg", ".jpg" };
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
try
{
string s_newfilename = DateTime.Now.Year.ToString() +
DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() +
DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + DateTime.Now.Second.ToString() + fileExtension;
fu.PostedFile.SaveAs(filepath + s_newfilename);
imagepath = ImageSavedPath + s_newfilename;
}
catch (Exception ex)
{
Response.Write("File could not be uploaded.");
}
}
}
}
return imagepath;
}
I refer to post # ASP.NET - Limit file upload available file types
Using RegularExpressionValidator can solve the problem easily. No serverside code is necessary for the checking of the extension anymore. Copy & Paste this code
<asp:RegularExpressionValidator ID="uplValidator" runat="server"
ControlToValidate="FileUpload1" ErrorMessage=".mp3, .mp4 & wma formats are allowed"
ValidationExpression="(.+\.([Mm][Pp][3])|.+\.([Mm][Pp][4])|.+\.([Ww][Mm][Aa]))">
</asp:RegularExpressionValidator>
I think it is not possible with <input type="file" control.
I've heard about SWFUploader that allows to define extensions for files to upload, but this is a flash-based component.
And even if you use SWFUploader, nothing will prevent you against typing *.*, and selecting any file to upload.
You can use C1Upload from ComponentOne to do this. It has support for file type and size validation. Keep in mind, you will want to also validate on the server since file extensions can easily be changed to mismatch their actual type. This is a standard in any validation practice: validate in the UI layer then validate at the BL layer and preferably validate at the DL too. Here is a demo of the ASP.NET AJAX upload control with built-in validation.
Another cool thing about this control is that is supports multiple upload files and shows upload progress!
when using Angular File Upload , this way you ca pass filters to uploder
.html file
<input type="file" nv-file-select uploader="uploaderImages" />
.js file:
$scope.uploaderImages.filters.push({
name: 'imageFilter',
fn: function (item/*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1;
}
});