I have images in folder /wwwroot/upload.
When I run my application on some pages I can see images on others I can see just crashed ones.
These are example GET methods after typing F12:
GET http://localhost:55975/Article/Edit/upload/7d69d935-0ab6-4e82-878f-c19595889004_marynarka.jpg
404 (Not Found)
GET http://localhost:55975/upload/45d9754e-d7e6-4f97-9653-2746304d5b1e_spodnie.jpg
200 OK (from disk cache)
GET http://localhost:55975/Article/Details/upload/297aa78a-64b1-454a-aa26-04eab0897511_szafa.jpg
404 (Not Found)
Edit:
In my code I have ArticleController and inside it are Details and Edit methods.
Edit.cshtml:
#model Shop.Models.Article
...
<img src="#(Model.Image)"/>
...
Details.cshtml:
#model Shop.Models.Article
...
<img src="#(Model.Image)"/>
...
Index.cshtml:
#model IEnumerable<Shop.Models.Article>
#foreach (var item in Model) {
<tr>
<td>
<img src="#(item.Image)" width="70px" height = "70px"/>
</td>
</tr>
Part of CreateArticle method:
if(image != null)
{
string uniqueName = Guid.NewGuid().ToString() + "_" + Path.GetFileName(image.FileName);
var name = Path.Combine(_hostingEnvironment.WebRootPath + #"\upload", uniqueName);
image.CopyTo(new FileStream(name, FileMode.Create));
article.Image = "upload/" + uniqueName;
}
if(image == null)
{
article.Image = "noimage/NoImage.png";
}
The issue is with your image source attribute. When the image source is set to "uploads/imagename...", you are telling the browser to look for the uploads folder inside the current URL path (a "relative" path). That is why some of your image requests are looking for the uploads folder inside your controller route (e.g., /Article/Edit/uploads...).
Instead, set your image source in your view to "/uploads/..." to ensure that the uploads folder path is correct regardless of which controller or URL is used to get the page.
You can learn more about specifying paths here.
If you want to reference the static files in /wwwroot/upload.You can try to use src="~/{folder name in wwwroot}/{image name}",such as:
<img src="~/upload/xxx.png" width="70px" height = "70px"/>
You can refer to the offcial doc about static files in .net core.
Related
I have trouble with display a image in my Angular app.
This is in my profile.ts and profile.html page
public createImgPath = (serverPath: string) => {
return `http://localhost:63040/${serverPath}`;
}
<img class="img-responsive" src="{{createImgPath(userApi.user.imageUrl.folderName)}}" />
From the server I get filepath:
var folderName = Path.Combine( "userImages", fileName);
return Ok(new { folderName });
When I try to display image in src I get the path but image is not display.
And I got error message:
It was very silly typo mistake. Instead "usersImages", in var folderName I used to use "userImages". I'm sorry for trouble to everyone.
I think you're supposed to return the file as a blob. Because you cannot send your images as a JSON to angular. Well, at first, change your backend code to something like this:
var folderName = Path.Combine( "userImages", fileName);
return new FileStream(folderName , FileMode.Open, FileAccess.Read);
and then change [HttpGet] to [HttpPost]
I don't know how to send your image file to the backend but I think you can fix your problem with these changes.
I have few links to pdf files store in server in my static page. I would be able to click each link that would open a pdf file in browser. I referred to this link. But it is not working as I intended.
Here is my action method:
public ActionResult GetFileFromServer(string filename)
{
string folderpath = StrGlobal.file_folder.ToString();
string filepath = Path.Combine(folderpath, filename);
filepath = Path.GetfullPath(filepath);
return File(filepath, "application/pdf");
}
My view:
<p>
#Html.ActionLink(
linkText: "ABC Document",
actionName:"GetFileFromServer",
controllerName:"StaticPage",
routeValues:new {filename = "ABC.pdf"},
htmlAttributes:null
)
</p>
If I replace and hardcore filename in this line:
string filepath = Path.Combine(folderpath, "ABC.pdf");
It will open that specific pdf file. Otherwise I get an error saying
Value cannot be null. Parameter name: path2
Seems like value is not getting passed from view to controller. How do I fix this issue?
<a href="/staticpath/ABC.pdf" download>
Donloadpdf
</a>
Hi,
We can resolved issue by easy way with using html download functionality.
I have MVC application which is having browse button I'm selecting file any location and reading file content using path and then process the content.
Works fine in local but when published on azure as web app obvious it was not able to get the file system path but how to handle this?
Could not find file 'D:\Windows\system32\mydata.json'.
Index.cshtml
<label>File Path</label>
<table>
<tr>
<td>#Html.TextBoxFor(m => m.filePath, new { type = "file", #class = "input-file" }) )</td>
<td> </td>
</tr>
</table>
HomeController.cs
private static void Test(string filepath)
{
string data = System.IO.File.ReadAllText(filepath);
JArray array = JArray.Parse(data);
On Azure the process current working directory is D:\Windows\system32\, try var wholePath = Path.Combine(Server.MapPath("~/"), filepath); to locate files under web root.
Update
Add HttpPostedFileBase field to your Model. In your View, change to m => m.File.
public class FileModel
{
public HttpPostedFileBase File { get; set; }
}
In Controller
public ActionResult FileUpload(FileModel fileModel)
{
if (ModelState.IsValid)
{
StreamReader s = new StreamReader(fileModel.File.InputStream);
JArray array = JArray.Parse(s.ReadToEnd());
...
}
return View();
}
You're trying to read a file that is on a client machine in code that's executing on the server. That won't work. Your server doesn't have access to files in the client machine. Which is a good thing 😁
Have a look at HttpPostedFileBase to upload files.
I have a simple Action which should allow me to download an asked file.
This works perfectly if I call the action using the browser's context menu (see the screenshot below), but when I click the link directly I get the following error: HTTP Error 404.0 - Not Found - The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Using browser's context menu:
Controller Action for downloading files:
public ActionResult Download(string id)
{
string username = User.Identity.Name;
Client client = db.Client.SingleOrDefault(x => x.Email == username);
string filePath = Server.MapPath("~/Client-Documents/" + client.FolderName + "/" + id);
return File(filePath, "text/plain", id);
}
View snippet where the file links are being generated:
#for (int i = 0; i < Model.Count(); i++)
{
<tr>
<td>#(i + 1)</td>
<td>#Model[i].Name</td>
<td>
Download
</td>
</tr>
}
You were passing the filename which included the extension, so it was being ignored by ASP.NET and treated as a static file, thus resulting in a 404. To avoid this, don't pass the extension. Probably best to refer to the files by ID.
Also note that if the files are part of your data, it's probably best to store them in a database. This avoids many file system pitfalls.
I'm trying to upload a file from browser and copy it to a URL folder
using c sharp.
( i have all the Permissions to this folder)
i have no problam upload the file to my hard drive
like this:
HttpPostedFileBase myfile;
var path = Path.Combine(Server.MapPath("~/txt"), fileName);
myfile.SaveAs(path);
i have try to upload it to URL like this but i am getting an exception
HttpPostedFileBase myfile;
var path =VirtualPathUtility.ToAbsolute("http://localhost:8080/game/images/"+fileName);
myfile.SaveAs(path);
the Exception:
System.ArgumentException: The relative virtual path 'http:/localhost:8080/game/images/ a baby bottle. Jpg' is not allowed here.
In - System.Web.VirtualPath.Create (String virtualPath, VirtualPathOptions
You cannot upload the file to a remote location. If you want this to work you will have to modify the remote server so that it accepts file uploads, the same way your server accepts file uploads and then send an HTTP request to it using a WebClient. You cannot use the SaveAs method as it expects a local path.
You could have the following controller action:
[HttpPost]
public ActionResult Upload(HttpPostedFileBase myFile)
{
if (myFile != null && myFile.ContentLength > 0)
{
var fileName = Path.GetFileName(myFile.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data"), fileName);
myFile.SaveAs(path);
}
...
}
and a corresponding form with a file input:
#using (Html.BeginForm("Upload", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<input type="file" name="myFile" />
<button type="submit">Click this to upload the file</button>
}
You should use Server.MapPath("Path")
var path = Server.MapPath("~/images/") + fileName);
myfile.SaveAs(path);