私は現在、以前の請負業者が私たちのサイト内の添付領域を持っていたプロジェクトに取り組んでいます。この部分はほとんどの場合動作しますが、ファイルをアップロードした後にリダイレクトする際に問題があります。また、アップロードされたファイルを表示するためにグリッドを更新するために、ページ全体がリロードされるのは嫌です。AjaxからHttpPostedFileBaseとFormCollectionを渡す
私の目標は、アップロードとフォームの送信の代わりにAjaxを呼び出すことです。私はこれを追加しましたが、リターンはJsonオブジェクト(IE 11を使用)のダウンロードを強制します。私はこれを回避する方法を研究し、まだそれを取り巻く実質的な方法を見つけていない。
Ajaxを使用してファイルをアップロードできますが、Jsonオブジェクトのダウンロードを返すことはできませんか?
以下は私のコードです。
ビュー(Upload.cshtml)
@using (Html.BeginForm("Upload", "PM", FormMethod.Post, new { enctype = "multipart/form-data", id = "frmUpload" }))
{
@Html.ValidationSummary(true)
<table>
...
<tr>
<td>@Html.Label("File: ")</td>
<td>
<input type="file" name="file" id="file"/>
@Html.ValidationMessage("file","File is required")
</td>
</tr>
...
<tr>
<td colspan="2">
<p>
<button type="submit" class="t-button" id="btnSubmit">
Attach</button>
<button type="button" class="t-button" onclick="CloseAttachmentWindow()">
Cancel</button>
</p>
</td>
</tr>
</table>
}
<script type="text/javascript">
$(document).ready(function() {
$("#btnSubmit").click(function (e) {
e.preventDefault();
if (!$('form').valid())
return false;
//Upload document
$.ajax({
type: "POST",
cache: false,
url: "/PM/Upload",
dataType: "json",
contentType: false,
processData: false,
data: $('form').serialize(),
success: function (result) {
if (result.success) {
var window = $("#error").data("tWindow");
window.content("<b>Attachment successfully added</b>").title("Success!");
window.center().open();
CloseAttachmentWindow();
}
else {
var window = $("#error").data("tWindow");
window.content("<b>Error: Unable to Upload Document. Please try again. "
+ "If this fails, contact the administrators with the below details.</b>"
+ '\n' + '\n' + result.Error).title("Error");
window.center().open();
}
},
error: function (xhtr, e, e2) {
var window = $("#error").data("tWindow");
window.content(e + '\n' + xhtr.responseText, 'error', '');
window.center().open();
}
});
});
});
</script>
PMController.csの通りです
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file, FormCollection formcollection)
{
if (file != null)
{
var cntPOC = int.Parse(Session["cntPOC"].ToString());
try
{
var cntFileType = _fileTypeRepo.GetCntFileTypeByMimeType(file.ContentType);
if (cntFileType == 0)
throw new Exception("This file type is not supported");
var strAttachmentName = formcollection["AttachmentName"];
var strAttachmentType = formcollection["AttachmentType"];
var length = file.ContentLength;
var tmpFile = new byte[length];
if (tmpFile.Count() > 0)
{
file.InputStream.Read(tmpFile, 0, length);
var intAttchmentId = _AttachRepo.GetNextAttachmentId() + 1;
var objAttachment = new TBLATTACHMENT
{
CNTATTACHMENT = intAttchmentId,
CNTPOC = cntPOC,
CNTFILETYPE = cntFileType,
CNTATTACHMENTTYPE = Convert.ToDecimal(strAttachmentType),
DTMCREATED = DateTime.Now,
STRATTACHMENTTITLE = strAttachmentName,
BLBATTACHMENT = tmpFile,
STRORIGINALFILENAME = file.FileName,
YSNDELETED = 0
};
_AttachRepo.Add(objAttachment);
_AttachRepo.Save();
return Json(new { success = true, Error = "" });
}
//File not real
else
return Json(new { success = false, Error = "Please select appropriate file" });
}
catch (Exception ex)
{
logger.LogError("File Upload", ex);
if (ex.InnerException != null)
ModelState.AddModelError("Error", ex.InnerException.ToString());
else
ModelState.AddModelError("Error", ex.Message.ToString());
TempData["ModelState"] = ModelState;
return Json(new { success = false, Error = ex.Message });
}
}
else
{
logger.LogError("File Upload Error. File was not selected");
ModelState.AddModelError("Error", "Please select file");
TempData["ModelState"] = ModelState;
return Json(new { success = false, Error = "File was not selected" });
}
}
は、このコードを使用して、私はドキュメントをアップロードすることができ、しかし、私は、JSONオブジェクトをダウンロードするためのプロンプトを取得します復帰時に
ここにあなたのお問い合わせ内容が明確ではありません。まず、表示されたコード( 'data:$( 'form')。serialize()、')を使ってファイルをアップロードすることはできません。このファイルはPOSTメソッドで常に 'null'になります。あなたは 'FormData'を使用する必要があります([この回答を参照してください(http://stackoverflow.com/questions/29293637/how-to-append-whole-set-of-model-to-formdata-and-obtain-it- in-mvc/29293681#29293681))。 –
そして、あなたは何を意味しますか?戻り値はJsonオブジェクトのダウンロードを強制しますか? (あなたの '@ Html.ValidationMessage(" file "、" File is required "))は意味がありません。入力と返すjsonには' data-val- * '属性はありません。 –