This approach will work on almost all browsers but, you can't upload multiple files, and file information have to send separately. In this method file is send directly in XMLHttpRequest, and file information is send along with HTTP Headers.
js FILE
js FILE
- window.onload = function () {
- document.getElementById('uploader').onsubmit = function () {
- var fileInput = document.getElementById('fileInput');
- var xhr = new XMLHttpRequest();
- xhr.open('POST', '/Home/Upload');
- xhr.setRequestHeader('Content-type', 'multipart/form-data');
- //Appending file information in Http headers
- xhr.setRequestHeader('X-File-Name', fileInput.files[0].name);
- xhr.setRequestHeader('X-File-Type', fileInput.files[0].type);
- xhr.setRequestHeader('X-File-Size', fileInput.files[0].size);
- //Sending file in XMLHttpRequest
- xhr.send(fileInput.files[0]);
- xhr.onreadystatechange = function () {
- if (xhr.readyState == 4 && xhr.status == 200) {
- alert(xhr.responseText);
- }
- }
- return false;
- }
- }
- [HttpPost]
- public JsonResult Upload()
- {
- string fileName = Request.Headers["X-File-Name"];
- string fileType = Request.Headers["X-File-Type"];
- int fileSize = Convert.ToInt32(Request.Headers["X-File-Size"]);
- //File's content is available in Request.InputStream property
- System.IO.Stream fileContent = Request.InputStream;
- //Creating a FileStream to save file's content
- System.IO.FileStream fileStream = System.IO.File.Create(Server.MapPath("~/") + fileName);
- fileContent.Seek(0, System.IO.SeekOrigin.Begin);
- //Copying file's content to FileStream
- fileContent.CopyTo(fileStream);
- fileStream.Dispose();
- return Json("File uploaded");
No comments:
Post a Comment