在服务器端访问ajax post表单数据
本文关键字:表单 数据 post ajax 服务器端 访问 | 更新日期: 2023-09-27 18:28:28
我正试图在上传文件的同时发布一些数据。作为第一次尝试,我尝试将希望在服务器端检索的所有数据作为参数传递。尽管我设法正确地检索了参数"Mode"的值。我从未收到参数"file"的值。我不知道为什么?
以下是我的代码:
控制器:
public ActionResult ReadFromExcel(HttpPostedFileBase file, bool Mode)
{
// file is always null
// Mode receives the correct values.
}
脚本:
$(document).ready(function () {
$("#ReadExcel").click(function () {
var overwritefields = $("#overwritefields").is(":checked");
$.ajax({
type: "POST",
url: 'ReadFromExcel',
data: '{"file":"' + document.getElementById("FileUpload").files[0] + '","Mode":"' + overwritefields + '"}',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
// Refresh data
},
error: function (error) {
alert("An error occured, Please contact System Administrator. 'n" + "Error: " + error.statusText);
},
async: true
});
});
然后我尝试通过Request.file[0]访问文件,这在一定程度上是成功的。但是,如何检索其他表单数据(如"Mode")的值?
以下是我的代码:
控制器:
public ActionResult ReadFromExcel()
{
var file = Request.Files[0].
// file contains the correct value.
// Unable to retrieve mode value though.
}
脚本:
$(document).ready(function () {
$("#ReadExcel").click(function () {
var formData = new FormData();
formData.append("FileUpload", document.getElementById("FileUpload").files[0]);
var overwritefields = $("#overwritefields").is(":checked");
formData.append("Mode", overwritefields);
$.ajax({
type: "POST",
url: 'ReadFromExcel',
data: formData,
dataType: 'json',
contentType: 'application/json; charset=utf-8',
processData: false,
success: function (response) {
// Refresh data
},
error: function (error) {
alert("An error occured, Please contact System Administrator. 'n" + "Error: " + error.statusText);
},
async: true
});
});
以下是我的观点:
@model IPagedList<Budget>
@{
ViewBag.Title = "Import Budget Line Items From Excel";
var tooltip = new Dictionary<string, object>();
tooltip.Add("title", "Click to import budget line items from Excel");
int pageSize = 10;
string sortname = "ItemCode";
string sortorder = "asc";
string filter = "";
bool hasFilter = false;
if (Session["BudgetImportGridSettings"] != null)
{
//
// Get from cache the last page zise selected by the user.
//
Impetro.Models.Grid.GridSettings grid = (Impetro.Models.Grid.GridSettings)Session["BudgetImportGridSettings"];
pageSize = grid.PageSize;
sortname = grid.SortColumn;
sortorder = grid.SortOrder;
filter = grid.HasFilter ? grid.FilterString : "";
hasFilter = grid.HasFilter && grid.Filter.rules.Count > 0;
}
}
<h2>@ViewBag.Title</h2>
<br style="clear: both;" />
<input type="file" id="FileUpload" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />
<span class="buttonspan backtolist" id="ReadExcel" title="Click to import budget line items from Excel"><a href="#" title="Click to import budget line items from Excel">Import</a></span>
<br style="clear: both;" />
<br style="clear: both;" />
<input type="checkbox" id="overwritefields" title="Overwrite other fields with imported non-blank data" class="chkclass" value=false />
<br style="clear: both;" />
<br style="clear: both;" />
@Html.Partial("_BudgetImportGrid")
<input type="hidden" value="@ViewBag.BudgetType" id="IntBudgetType" />
一个简单的方法就是将bool mode
添加到操作方法中:
public ActionResult ReadFromExcel(bool Mode)
{
//Use the selected Mode...
var file = Request.Files[0].
// file contains the correct value.
// Unable to retrieve mode value though.
}
我希望您可以使用HTML5文件阅读器API。以下解决方案使用它:
我从头开始构建了您的场景,以确保我的建议有效。
摘要:
- CCD_ 2作为动作方法参数。它是使用查询字符串提供给服务器的
- 作为二进制请求主体的一部分上载的文件。使用FileReader HTML5 API获得二进制数据。这是显而易见的HTML5部分,如果你能替换它,那么你可能会得到HTML5的依赖性
- AJAX是POST请求
使用以下JavaScript:
$(function(){
$("#upload").click(function () {
var overwritefields = $("#overwritefields").is(":checked");
var r = new FileReader();
r.onload = function () {
$.ajax({
type: "POST",
url: 'UploadFileWithBoolean?mode=' + overwritefields,
data: r.result,
contentType: 'application/octet-stream',
processData: false,
success: function (d) {
console.log("ok");
console.log(d);
},
error: function (d) {
console.log("fail");
console.log(d);
},
async: true
});
};
r.readAsBinaryString(document.getElementById("FileUpload").files[0]);
});
});
控制器方法:
[HttpPost]
public ActionResult UploadFileWithBoolean(bool mode)
{
//your file is now in Request.InputStream
return Json(new { message = "mode is " + mode.ToString(), filesize = Request.InputStream.Length });
}
让我知道这是否有帮助。感谢