how to upload a file to url - c#

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);

Related

How to use uploaded files from .net core API in my angular application?

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.

Links for pdf files in server from static mvc web application

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.

How to return an image from wwwroot?

I'm trying to return an image stored inside wwwwroot/images folder, this is the structure:
Inside the View I have the following tag:
<img src="#Url.Action("GetAvatar", "User", new { username = User.Identity.Name })" />
as you can see for display the image it simply call GetAvatar method from User controller passing the username as parameter.
The method have the following configuration:
[HttpGet]
public FileResult GetAvatar(string username)
{
User user = _repo.GetUser(username);
if(user.UserDetail != null)
return File(user.UserDetail?.UserPhoto, "image/png");
//The user has no custom image, will displayed the default.
string root = Path.Combine(_env.WebRootPath, "images");
return File(Path.Combine(root, "avatar_default.png"), "image/png");
}
the firtst part of the method that retrieve the image from the database works, but the last part which try to get the image from the wwwroot folder doesn't work. Infact when I load the View I get the broked thumbnail which mean not found.
I'm also injected the IHostingEnvironment for access to wwwroot folder.
Any idea?
The File method you're using has the following signature:
public VirtualFileResult File (string virtualPath, string contentType);
As its name suggests, the first parameter here represents the virtual path of the file you want to serve; not the physical path. By default, this means you need to provide a path that is essentially just relative to the wwwroot folder. In your example, the path would be images/avatar_default.png. With this, there's no need for Path.Combine or IHostingEnvironment in your example. Here's the updated version:
[HttpGet]
public FileResult GetAvatar(string username)
{
User user = _repo.GetUser(username);
if(user.UserDetail != null)
return File(user.UserDetail?.UserPhoto, "image/png");
return File("images/avatar_default.png", "image/png");
}

Need uploaded file path to convert to Byte[]

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.

Open external PDF file in asp.net MVC 2

I know how to open an internal pdf file :
public ActionResult GetPDF( string filename )
{
return File( filename, "application/pdf", Server.HtmlEncode( filename ) );
}
question is, how to open a PDF file from an other/external website, e.g. http://example.com/mypdffile.pdf
You don't really need a controller action to do this. You could simply:
Open mypdffile.pdf
Of course if you want to hide this address from the user you could use a WebClient to fetch it on the server:
public ActionResult GetPDF()
{
using (var client = new WebClient())
{
var buffer = client.DownloadData("http://www.blabla.com/mypdffile.pdf");
return File(buffer, "application/pdf", "mypdffile.pdf");
}
}
And in your view:
<%= Html.ActionLink("Download PDF", "GetPDF") %>
You will need it locally anyway to do any processing so, you can download it to local folder and then show it. use WebClient or HttpRequest/HttpResponse objects to do the downloading

Categories

Resources