Click here to Skip to main content
15,918,258 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
How do i read files form html control to C# code and how to save in server?

I have one html input control in my html page. When i click on upload i want to save that file in server folder using .net code. but how can i read and save that file.
Below is my code,
Angular js side code,
function RRUplaod() {
var File;
File = $('#FileUpload')[0].files[0];
if (File != "") {
var fileName = File.name;
fileName = fileName + '^' + id
var xhr = new XMLHttpRequest();
var url = //service url
xhr.open('POST', url, true);
xhr.setRequestHeader("FN", fileName);
inviteFileName = fileName;
xhr.onreadystatechange = function () {
};
xhr.send(File);
}

C# code

C#
public UploadedFile UplaodFile(Stream Uploading)
   {
          IncomingWebRequestContext woc = WebOperationContext.Current.IncomingRequest;
           WebHeaderCollection headers = woc.Headers;
           string fileName = "";
           string id= "";

           fileName = headers["FN"].Split('^')[0];
           id= headers["FN"].Split('^')[1];

           UploadedFile upload = new UploadedFile
           {
               FilePath = Path.Combine(HttpContext.Current.Server.MapPath(".") + "\\Document\\", fileName)
           };


           FileStream fs = new FileStream(upload.FilePath, FileMode.Open, FileAccess.Read);
           byte[] ImageData = new byte[fs.Length];
           fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));
           fs.Close();

}

but i dont know how to save that file using c# code...
Please help
Posted
Comments
Sinisa Hajnal 9-Dec-15 6:57am    
What you're showing above IS C# code. What is the problem? Call write after read and put it in the path you have access to and that is all.
Nathan Minier 9-Dec-15 7:34am    
That's not how it works. You'll need to use some form of file uploading, such as an <input type="file" /> or use an Angular module like https://github.com/danialfarid/ng-file-upload .

On the server side, you'll need to use a Multipart Form parser in order to break the http request body into parts that can be operated on. You can write one if you really like, but that's a rabbit hole all on it's own.

If you're using MVC instead of WCF or WebAPI, there is an easier tool with the HttpPostedFileBase that will automatically parse the request body for you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900