The path value returns a root website path. However, I don't want to store images there, I want to get the image from the user (when they upload from local).
I can hard code the string with my local path and it will work but that wont work in other environments. I am running .net core 1.0.
Controller:
foreach (var file in files)
{
if (file.Length > 0)
{
string path = Path.GetFullPath(model.Filename);
var img = Image.FromFile(Path.Combine(path, file.FileName));
using (var ms = new MemoryStream())
{
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
model.FileData = ms.ToArray();
}
}
}
View:
<input asp-for="Filename" type="text" id="upload-banner" class="form-control" placeholder="Upload Image" readonly>
<span class="input-group-btn">
<input id="i_file" type="file" name="files" multiple />
<button type="button" class="btn btn-effect-ripple btn-primary">Upload</button>
</span>
You seem to be confused how file uploading works. The back end code does not have any access to the filesystem that is providing the file; instead, it comes over the HTTP pipeline. The back end code must accept the file and save it somewhere locally before you can work with it on the local file system.
Code like this might work:
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
See this link for a complete example.
Related
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.
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.
can somebody help me with problem that happen when i'm trying to send large file(256mb~) to azure blob. Error is OutofMemoryException. App is hosting in webApp on azure with 3.5gb ram plan.
Schema of transfering looks like:
-sending file from here
<form method="post" enctype="multipart/form-data" asp-controller="UploadFiles" asp-action="Post" style="margin-top: 100px;">
<div>
<p>Upload one or more files using this form:</p>
<input type="file" name="files" multiple />
</div>
<div>
<p>Your Username</p>
<input type="text" name="username" />
</div>
<div>
<input type="submit" value="Upload" />
</div>
controller:
public async Task<IActionResult> Post()
{
CloudStorageAccount storageAccount = CloudStorageAccount.Parse("");
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("testcontainer");
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");
FormValueProvider formModel;
formModel = await Request.StreamFile(storageAccount);
-stream file extension i took from example in microsoftdocs, inside it i put method that chunk memory stream on blockblob and send them as BlockList
var formAccumulator = new KeyValueAccumulator();
string targetFilePath = null;
var boundary = MultipartRequestHelper.GetBoundary(
MediaTypeHeaderValue.Parse(request.ContentType),
DefaultFormOptions.MultipartBoundaryLengthLimit);
var reader = new MultipartReader(boundary, request.Body);
var section = await reader.ReadNextSectionAsync();
while (section != null)
{
ContentDispositionHeaderValue contentDisposition;
var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out contentDisposition);
if (hasContentDispositionHeader)
{
if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition))
{
using (var stream = new MemoryStream())
{
await section.Body.CopyToAsync(stream);
stream.Position = 0;
await new AzureBlobUtil().UploadBlob(stream, blockBlob, "testcontainer", "testBlob");
}
i think problem is in memory stream, cause there storing whole file before sending to azure, but i dont know how to chunk it. I mean idk how to send part of MultipartReader.
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);