html Ajax文件上传(JQuery和ASP.Net MVC).html
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了html Ajax文件上传(JQuery和ASP.Net MVC).html相关的知识,希望对你有一定的参考价值。
//-------------------------------------- CONTROLLER METHOD ----------------------
// JSUT RECEIVE A PARAMETER WITH TYPE 'HttpPostedFileBase license=null' and do uploadings
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using VelocityFinCrime.Common;
namespace VelocityFinCrime.Web.Areas.Admin.Controllers
{
public class LicensingController : Controller
{
public ActionResult Index()
{
var KeyValuePairs = EncryptionUtil.DecryptFile(EncryptionUtil.EncFilePath, '|', '=', EncryptionUtil.EncKeySize);
int expDateInt = KeyValuePairs["ExpiryDate"];
DateTime expDate = new DateTime(expDateInt / 10000, (expDateInt / 100) % 100, expDateInt % 100);
ViewBag.MaxBranch = KeyValuePairs["MaximumNumberOfBranch"];
ViewBag.MaxUser = KeyValuePairs["MaximumNumberOfUser"];
ViewBag.ExpDate = expDate.ToString("dd MMMM yyyy");
return PartialView();
}
public ActionResult RenewLicense(HttpPostedFileBase license = null)
{
bool validFile = true;
try
{
BinaryReader b = new BinaryReader(license.InputStream);
byte[] binData = b.ReadBytes(Convert.ToInt32(license.InputStream.Length));
var KeyValuePairs = EncryptionUtil.DecryptFromStream(binData, '|', '=', EncryptionUtil.EncKeySize);
if (! KeyValuePairs.ContainsKey("MaximumNumberOfBranch") || !KeyValuePairs.ContainsKey("MaximumNumberOfUser") || !KeyValuePairs.ContainsKey("ExpiryDate")) validFile = false;
}
catch(Exception ex)
{
validFile = false;
}
if (!validFile)
{
return Json(new
{
message = "Invalid/Damaged License File!"
});
}
else
{
if (Request.Files.AllKeys.Any())
{
license = Request.Files["license"];
}
if (license != null && license.ContentLength > 0)
{
var path = EncryptionUtil.EncFilePath;
license.SaveAs(path);
}
return Json(new
{
message ="License Uploaded Successfully!!!"
});
}
}
}
}
<style>
input[type="file"] {
display: none;
}
.custom-file-upload {
border: 1px solid #ccc;
display: inline-block;
padding: 6px 12px;
cursor: pointer;
color: white;
background: #405161;
}
</style>
<div class="clearfix"></div>
<div class="row">
<div class="table-responsive">
<table id="dataTable" class="table table-bordered table-hover">
<thead>
<tr>
<th>Branch Limit</th>
<th>User Limit</th>
<th>Expiry Date</th>
</tr>
</thead>
<tbody>
<tr class="dataItem">
<td style="text-align: center;">@ViewBag.MaxBranch</td>
<td style="text-align: center;">@ViewBag.MaxUser</td>
<td style="text-align: center;">@ViewBag.ExpDate</td>
</tr>
</tbody>
</table>
</div>
</div>
<br />
@*@using (Html.BeginForm("RenewLicense", "Licensing", new {area = "admin"}, FormMethod.Post, new {enctype = "multipart/form-data", id = "fileForm", name = "fileForm"})){*@
<form action="@Url.Action("RenewLicense", "Licensing")" enctype="multipart/form-data" id="fileForm" method="post" name="fileForm">
<div id="UploadDiv" class="row form-horizontal report-form">
<h3>Renew License</h3>
<table style="width: 100%;" class="table table-hover">
<tr class="row">
<td>
<label for="license" class="custom-file-upload" style="font-weight: normal"><i class="fa fa-cloud-upload"></i> Select File</label>
<input id="license" type="file" name="license" class="btn-primary" /><br />
<div class="col-xs-7" style="margin: 0 !important; padding: 0 !important;">
<span class="form-control" id="CustomerFile" value="No File Selected" style="margin-top: 5px;" >No File Selected! </span>
</div>
<div class="col-xs-8" style="margin: 10px 0px 0px 0px !important; padding: 0 !important;">
<input type="button" id="btnRenew" class="btn btn-primary" style="width: 100px;" value="RENEW">
</div>
</td>
</tr>
</table>
</div>
</form>
<script type="text/javascript">
$(document).ready(function () {
$("#btnRenew").click(function () {
debugger;
var obj = validateFileUpload();
if (!obj.valid) bootbox.alert(obj.msg);
else {
var formData = new FormData();
var file = document.getElementById("license").files[0];
formData.append("license", file);
// WORKING ALSO
//var data = new FormData($('form')[0]);
//data.append(this.name, this.value);
$.ajax({
type: "POST",
url: '/Admin/Licensing/RenewLicense',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
beforeSend: function () {
Spiner.show();
},
success: function (response) {
//console.log(response);
Spiner.hide();
bootbox.alert(response.message);
},
error: function (error) {
//console.log(error);
Spiner.hide();
bootbox.alert(response.message);
}
});
}
});
function validateFileUpload() {
var obj = { valid: true, msg: "<strong>Make sure these when uploading: </strong><br>" };
var allowedExtensions = ['txt', 'dll', 'lic'];
if (document.getElementById("license").files[0] === undefined) { obj.valid = false; obj.msg += "<strong>*</strong>. Please select a file!<br>"; }
if (getFileSize("#license") > 100) { obj.valid = false; obj.msg += "<strong>*</strong> More than 100 KB file is not allowed!<br>"; }
if ($.inArray($("#license").val().split('.').pop().toLowerCase(), allowedExtensions) == -1) {
obj.valid = false; obj.msg += "<strong>*</strong> Only formats are allowed : " + allowedExtensions.join(', ') + "<br>";
}
return obj;
}
$("#license").change(function () {
var obj = { valid: true, msg: "</strong>Invalid File: </strong><br>" };
var fileExtension = ['txt', 'dll', 'lic'];
if (getFileSize("#license") > 100) {
obj.msg += "<strong>*</strong> More than 100 KB file is not allowed, Please select a license file!<br/>";
obj.valid = false;
}
if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
obj.msg += "<strong>*</strong> Only formats are allowed : " + fileExtension.join(', ') + "<br/>";
obj.valid = false;
}
if (obj.valid === false) bootbox.alert(obj.msg);
$("#CustomerFile").html($('input[type=file]').val().replace(/.*(\/|\\)/, '') + " <strong>(" + getFileSize("#license") + " KB)<strong>");
});
function getFileSize(id) {
var iSize = ($(id)[0].files[0].size / 1024);
iSize = (Math.round(iSize * 100) / 100);
return iSize;
}
});
</script>
以上是关于html Ajax文件上传(JQuery和ASP.Net MVC).html的主要内容,如果未能解决你的问题,请参考以下文章
jQuery ajax 在 asp.net mvc 中上传文件
[Asp.net mvc]jquery.form.js无刷新上传
如何在 ASP.NET MVC 中处理 HTML5 多文件上传?