File Upload And Download By Using Linq
We
start by creating a new ASP.NET MVC 3 web application and we add the file
“jquery-filedrop.js” to the Scripts folder of the project. After this is done
we modify the default layout “Views/Shared/_Layout.cshtml” to reference our
newly added JavaScript library. In order to do is, add the following line to
the head tag.
<script src="@Url.Content("~/Scripts/jquery.filedrop.js")" type="text/javascript"></script>
Controller Class::
Home.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
namespace MVC3FileUploadDownloadLINQ.Controllers
{
public class HomeController : Controller
{
//
// GET: /Home/
private const string TempPath = @"D:\Temp";
public ActionResult
Index()
{
return View();
}
[HttpPost]
public ActionResult
UploadFiles(IEnumerable<HttpPostedFileBase> files)
{
foreach (HttpPostedFileBase
file in files)
{
string
filePath = Path.Combine(TempPath,
file.FileName);
System.IO.File.WriteAllBytes(filePath,
ReadData(file.InputStream));
}
return Json("All
files have been successfully stored.");
}
private byte[]
ReadData(Stream stream)
{
byte[] buffer = new byte[16 * 1024];
using (MemoryStream
ms = new MemoryStream())
{
int read;
while ((read = stream.Read(buffer, 0,
buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
}
}
Views: File drag and drop in your jquery drop box and automatically it's dowload after droping your file...
Index.cshtml
@{
ViewBag.Title = "Index";
}
<style type="text/css">
#dropZone {
background: gray;
border: black dashed 3px;
width: 200px;
padding: 50px;
text-align: center;
color: white;
}
</style>
<script type="text/javascript">
$(function () {
$('#dropZone').filedrop({
url: '@Url.Action("UploadFiles")',
paramname: 'files',
maxFiles: 5,
dragOver: function () {
$('#dropZone').css('background', 'blue');
},
dragLeave: function () {
$('#dropZone').css('background', 'gray');
},
drop: function () {
$('#dropZone').css('background', 'gray');
},
afterAll: function () {
$('#dropZone').html('The file(s) have been uploaded successfully!');
},
uploadFinished: function (i, file,
response, time) {
$('#uploadResult').append('<li>' + file.name + '</li>');
}
});
});
</script>
<h2>File Drag & Drop Upload Demo</h2>
<div id="dropZone">Drop your files here</div>
<br/>
Uploaded Files:
<ul id="uploadResult">
</ul>
Thanks
Happy Coding
Regards
Ur's Jagan
No comments:
Post a Comment