why isn't my path true in Customer host? - asp.net-mvc

I write below code for uploading image in my app.I set path for uploading image. below code is full correctly in my system and company's server. but when i publish customer site . in host can't find this path and produce HTTP ERROR 404.0 -NOT Found.
`string pic = System.IO.Path.GetFileNameWithoutExtension(model.ImageUpload.FileName) + Guid.NewGuid() + System.IO.Path.GetExtension(model.ImageUpload.FileName);
string path = System.IO.Path.Combine(
Server.MapPath("~"), "Areas/Administrator/uploads/", pic);
string PicPath = System.IO.Path.Combine("/Areas/Administrator/uploads", pic);
PicPath = PicPath.Replace("\\", "/");
model.ImageUpload.SaveAs(path);
bImageUpload.Inser(new Shared.Entities.SMP.ImageUpload
{
Title = model.Titel,
Lang = CultureHelper.GetLangFromCulture(),
ImageUrl = PicPath
});`

Does your folder exist?
Simulate the error:
Bring the image out of the folder into project files like this:
Server.MapPath("~/image.jpg"))
then run your project as a test.

Related

How can I set the name for a file that is to be downloaded in a Koa response?

I make a image proxy (to download a image not open) use node and koa.
the url /proxy/image code is :
...
const PassThrough = require('stream').PassThrough
let query = qs.parse(url.parse(ctx.request.url).query)
let passThroughStream = new PassThrough()
ctx.body = request(query.src).pipe(PassThrough())
...
The image downloaded name is image, but I want to rename the image, how could I do?
If I understand your question correctly, you should be able to do this by using ctx.attachment() which is an alias for ctx.response.attachment(). So you can do something like:
ctx.attachment('my-image.png')
This attachment method is basically a shorthand of the following header:
ctx.set('Content-disposition', 'attachment; filename=my-image.png');

MVC download images from ftp and show in VIew

Have some pictures on ftp location. My controller is getting list of paths for some specific images placed on ftp. What i want to do is to use those paths to download those pictures to local temporary folder and then show them inside gallery in view. Currently i am struggling with model to download those pictures but have some problems when trying to download pictures. Error posted below as well as current code. There is also folder creation code missing.
This is my controller method which would get paths list then calling download method to download pictures from ftp location to some temporary folder (and this temporary folder should be besides my application that then view could open images from that folder:
Function Details(Optional ByVal id As Long = Nothing) As ActionResult
'--Temporary directory for pictures to be downloaded from ftp location (temp_dir) should be created besides application folders
Dim temp_dir As String = "/temp_dir/"
'--If not temp_dir exist ==> create this folder
'--if folder has been created properly go all next lines..
'--Take list of all ftp paths e.g \someFolderForPictures\image1.jpg to be downloaded to temp_dir
Dim PicsTrans As List(Of tblTransPics) = db.tblTransPics.Where(Function(f) f.IdTrans = id).ToList
'--For each picture path download it to temp_dir folder with temporary name
For Each imgFtpPath In PicsTrans
Dim temp_picName As String = Guid.NewGuid.ToString
DownloadFile(imgFtpPath.PicturePath, temp_dir & temp_picName)
Next
'-- If everythings went well - pass either temp_dir path to view and inside view those pictures will be opened or pass list of pictures (bytes)???
Return View(temp_dir)
End Function
Download file method:
Public Function DownloadFile(ByVal ftpPicLocation As String, destinationLocation As String) As Boolean
Dim reqFTP As FtpWebRequest
Try
reqFTP = DirectCast(FtpWebRequest.Create("ftp://someftpserver.com" & ftpPicLocation), FtpWebRequest)
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile
reqFTP.UseBinary = True
reqFTP.Credentials = New NetworkCredential("myusername", "somepassword")
Using outputStream As New FileStream(destinationLocation, FileMode.OpenOrCreate)
Using response As FtpWebResponse = DirectCast(reqFTP.GetResponse(), FtpWebResponse)
Using ftpStream As Stream = response.GetResponseStream()
Dim bufferSize As Integer = 2048
Dim readCount As Integer
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
readCount = ftpStream.Read(buffer, 0, bufferSize)
While readCount > 0
outputStream.Write(buffer, 0, readCount)
readCount = ftpStream.Read(buffer, 0, bufferSize)
End While
End Using
End Using
End Using
Return True
Catch ex As Exception
Throw New Exception("Failed to download", ex.InnerException)
End Try
End Function
the error occurs on this line:
Using outputStream As New FileStream(destinationLocation, FileMode.OpenOrCreate)
and it says:
Cannot find part of path „C:\temp_dir\f0f43089-4a16-4229-8ea6-2c3a55fde2ae”.
By the way how there could be C:\ ?
Remove first slash in your temp_dir variable.
Dim temp_dir As String = "temp_dir/"
With this slash it means you want to write into your root. Your root equals C:\
By removing the first slash you get your temporary folder under the folder your application is running.

Roxy Fileman and Virtual Directorys

I have a solution with 2 projects in, one called "admin", the other say "work" (an Umbraco instance)
- Work has an images folder which contains the images for the site
banners/thumnails etc.
- Admin allows an admin user to add new stories, with images, using TinyMCE
and the fileman plug in.
So in IIS I created a virtual folder in Admin which points to the images folder in work, however when I try and browse the folder in fileman it repeats lots of sub directoriers and doesnt display any images.And I cannot upload any images either, it just gives me an error.
The Files_Root entry is as follows within the conf.json file.
"FILES_ROOT": ".//images//",
So how do I get this virtual folder to work with fileman?
I stumbled upon this problem as well - when the FILES_ROOT points to a virtual folder in IIS, the Fileman component chokes when trying to retrieve the list of files, and when uploading, and maybe some other places. The requests don't pass the folder location properly when it references a virtual directory. If you put a network sniffer on it, you'll see the requests sent to fileman/asp_net/main.ashx and the responses that come back with the error "The given path's format is not supported."
I've reported the bug to the author via the website, but I have also discovered that if you replace the virtual directory with a SYMLINK, everything seems to work.
If you have IIS access, you probably have command line access to create the symlink, which can be done as:
mklink /j "{virtual location within your website}" "{physical location}"
Both locations should be full paths, including drive letters and the "virtual" location should be in your website root.
So far, I have not seen an problems referencing files this way instead of with a virtual directory, other than that my site backups started including the files in the symlink, since the O/S sees that as a physical folder within the site now.
I hope this helps!!
Probably not good for every situation (maybe not even for the user that asked the question), but figured I would share in case it might help someone trying to get virtual directories mapped to network shares working. I needed to modify the ListDirTree function in file fileman/asp_net/main.ashx
protected void ListDirTree(string type)
{
string filesRoot = GetFilesRoot();
DirectoryInfo d = new DirectoryInfo( filesRoot );
if ( !d.Exists )
throw new Exception( "Invalid files root directory. Check your configuration: " + filesRoot );
ArrayList dirs = ListDirs( d.FullName );
dirs.Insert( 0, d.FullName );
string localPath = _context.Server.MapPath( "~/" );
bool isLocal = filesRoot.Contains( ":" );
_r.Write( "[" );
for ( int i = 0; i < dirs.Count; i++ )
{
string dir = (string)dirs[i];
string lPath;
//If it is a local path, leave it as it was
if ( isLocal )
lPath = dir.Replace( localPath, "" ).Replace( "\\", "/" );
else
//Otherwise probably a virtual directory, put the original files_root location back
lPath = dir.Replace( filesRoot, GetSetting( "FILES_ROOT" ) ).Replace( "\\", "/" );
_r.Write( "{\"p\":\"/" + lPath + "\",\"f\":\"" + GetFiles( dir, type ).Count.ToString() + "\",\"d\":\"" + Directory.GetDirectories( dir ).Length.ToString() + "\"}" );
if ( i < dirs.Count - 1 )
_r.Write( "," );
}
_r.Write( "]" );
}

How to avoid "Path Manipulation" error in Fortify? [duplicate]

I have path Manipulation problem. The following code is placed in Page_load method of ASPx page.
String rName = Request.QueryString["reportName"];
string path = "C:\\hari" + rName;
if (File.Exists(path))
{
File.Delete(path);
}
But Fortify scan report for the above sample code shows ‘Path Manipulation’ issue as high
Need help to modify above code so that it can pass fortify scan
Jackson is right, this is a direct File Path Manipulation vulnerability that can be fixed through indirect selection.
From your known directory, list all the files. Use the value coming from your own directory list, not the user-supplied value.
String rName = Request.QueryString["reportName"];
String knownPath = "C:\\hari";
DirectoryInfo di = new DirectoryInfo(knownPath);
FileInfo[] files = di.GetFiles(rName);
if (files.length > 0)
{
files[0].Delete();
}
I think the problem is that someone could spoof a request with reportName = "..\\Windows\\Something important" which is clearly a security flaw. You need to change your code so that it doesn't read a partial filename from the request query string.

Image not showing on IIS when MVC app is hosted on IIS..works on ASP.NET Devlopment server just fine

I have a view which looks like this
{{img src="/Scenario/Status/id" alt="status" /}}
(replace <> these {} above )
and this is the code in action of the controller
public ActionResult Status(int? id)
{
// Calculate the status
int no = new Random().Next(0, 2);
string file = "green.jpg";
if (no == 0)
{
file = "red.jpg";
}
else if (no == 1)
{
file = "yellow.jpg";
}
else if (no == 2)
{
file = "green.jpg";
}
var path = Server.MapPath("/Content/images/");
var filePath = path + file;
return new FileContentResult(System.IO.File.ReadAllBytes(filePath), "image/jpeg");
}
This works just fine when i run on visualstudio. But when i deploy it to local IIS, I dont see these images.
I checked that the "StaticContent" option is checked in Windows Features under IIS and also that the MIME type is enabled on IIS. I also checked that the *.jpg files are present under "inetpub" folder of my app after I publish from visual studio. Since i'm using virtual path for images and not hardcofing the filenames , it should work...
I just tried this
{{img src="../Content/Images/Green.jpg" alt="status" /}} and that works too.. :(
What else could be wrong?
A quick way to gain more insight into the problem would be to set a breakpoint in the Application_Error method of the global.asax, and see what exception is being raised when the request for the image comes in.
If you've deployed under a virtual directory in IIS, You'll need to use Server.MapPath("~/Content/images/")
Where Asp.Net will replace ~ with the application root.
Found the solution for displaying images in an app hosted in a sub folder unde root site on IIS
This worked..
img src = "<%= Url.Content("~/Home/GetRainfallChart") %>" alt="chart"
It is deployed to a virtual directory C:\inetpub\wwwroot\testsite....
Is that th eproblrm

Resources