[英]How to get a Response status while we submit a form to Web API
我有一個客戶端HTML應用程序和一個Asp.net WebAPI作為服務器應用程序。 我有一種情況,必須提交表單,並且作為“表單提交”的一部分,我需要將表單數據發布到數據庫。 這對我有用,但是客戶端應用程序如何知道在另一個域中發生的數據庫操作的成功或失敗狀態。 我試圖將HttpResponseMessage
對象返回給客戶端,但是我的整個HTML頁面被重寫為我從服務器返回的狀態。 是否有任何方法可以單獨檢查特定狀態,而不是使用從服務器API應用程序獲得的響應重寫整個HTML,以便在客戶端應用程序中擁有更多控制權?
提交表單的客戶代碼:
function ValidateFileAndSubmit() {
var myForm = $("#form1");
//UploadFiles();
var rootServicePath = config.rootURL;
var path = rootServicePath + 'api/Upload/UploadFile';
myForm.attr('action', path);
myForm.submit();
}
我訪問POST調用的Web Api代碼:
[HttpPost]
public HttpResponseMessage UploadFile()
{
HttpResponseMessage response = null;
if (HttpContext.Current.Request.Files.AllKeys.Any())
{
HttpContext.Current.Response.ContentType = "text/HTML";
var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
if (httpPostedFile != null)
{
// Validate the uploaded image(optional)
// Get the complete file path
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/UploadedFiles"), httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
response = new HttpResponseMessage(HttpStatusCode.Created)
{
Content = new StringContent("Uploaded Successfully")
};
}
}
return response;
}
這是完整的上傳測試案例:
布局
為了簡潔起見,我只放置必需的標記
<!DOCTYPE html>
<html>
<head>
<!-- Here you'll have all head child tags(meta, title, CSS related links ref tags and some other like modernizer scripts and other tags that required for app)-->
</head>
<body>
<!--navbar with Page heading title-->
<div class="container body-content">
@RenderBody()
<!--footer-->
</div>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<!--embed other global scripts here-->
@RenderSection("scripts", false)
</body>
</html>
UploadFilePage.css
body {
padding: 30px;
}
form {
display: block;
margin: 20px auto;
background: #eee;
border-radius: 10px;
padding: 15px;
}
.progress {
position: relative;
width: 400px;
border: 1px solid #ddd;
padding: 1px;
border-radius: 3px;
}
.bar {
background-color: #B4F5B4;
width: 0%;
height: 20px;
border-radius: 3px;
}
.percent {
position: absolute;
display: inline-block;
top: 3px;
left: 48%;
}
UploadFile查看標記
@{
ViewBag.Title = "Upload Demo";
}
<link href="~/Content/UploadFilePage.css" rel="stylesheet" type="text/css" />
<h2>Upload DEMO</h2>
<form action="/api/upload/UploadFile" method="post" enctype="multipart/form-data">
<input type="file" name="UploadedFile" /><br />
<input type="submit" value="Upload File to Server" />
</form>
<div class="progress">
<div class="bar"></div>
<div class="percent">0%</div>
</div>
<div id="status"></div>
@section scripts {
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
(function () {
var bar = $('.bar'), percent = $('.percent'), status = $('#status');
$('form').ajaxForm({
beforeSend: function () {
status.empty();
var percentVal = '0%';
bar.width(percentVal)
percent.html(percentVal);
},
uploadProgress: function (event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal)
percent.html(percentVal);
},
success: function (response) {
var percentVal = '100%';
bar.width(percentVal)
percent.html(percentVal);
alert(response);//its just for unit testing, pleae remove after your testing. This alert is not required as we are showing status on the page.
},
error: function (xhr) {
status.html(xhr.responseText || 'Error - File upload failed.');
},
complete: function (xhr) {
status.html(xhr.responseText);
}
});
})();
</script>
}
API控制器
為避免混淆,我在api-controller-action中應用了類似的邏輯
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
namespace TestCases.MVC.Controllers
{
public class UploadController : ApiController
{
[HttpPost]
public HttpResponseMessage UploadFile()
{
HttpResponseMessage response = null;
if (HttpContext.Current.Request.Files.AllKeys.Any()) {
HttpContext.Current.Response.ContentType = "text/HTML";
var httpPostedFile = HttpContext.Current.Request.Files["UploadedFile"];
if (httpPostedFile != null) {
// Validate the uploaded image(optional)
// Get the complete file path
var uploadFilesDir = HttpContext.Current.Server.MapPath("~/UploadedFiles");
if (!Directory.Exists(uploadFilesDir)) {
Directory.CreateDirectory(uploadFilesDir);
}
var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);
// Save the uploaded file to "UploadedFiles" folder
httpPostedFile.SaveAs(fileSavePath);
response = new HttpResponseMessage(HttpStatusCode.Created) {
Content = new StringContent("Uploaded Successfully")
};
}
}
return response;
}
}
}
您可以使用jQuery使用AJAX進行管理
AJAX(XHR2)FormData功能解決方案( 在此處檢查瀏覽器支持 )
假設:
JavaScript的:
<script type="text/javascript">
$(function() {
$('#btnUpload').click(function() {
if (window.FormData !== undefined) {
var formData = new FormData(),
yourFileObj = $('#fileInputField').get(0),
rootServicePath = config.rootURL,
urlPath = rootServicePath + 'api/Upload/UploadFile';
formData.append("UploadedImage", yourFileObj.files[0]);
$.ajax({
url: urlPath,
type: 'POST',
data: formData,
cache: false,
success: function(response) {
//do something with response
}
});
} else {
alert("your browser sucks!");
}
});
});
</script>
注意: FormData
是XMLHttpRequest Level 2
一部分。 在此處檢查xhr2跨瀏覽器支持 。
如果您正在尋找IE,它會從IE10+
支持。
為了支持IE9-
我們應該考慮使用后備方法(使用iframe
上傳)。
后備解決方案(AJAX(XHR2)FormData功能和iframe)
您可以使用現有的開源jQuery插件jquery.form.js
還要觀察下面的線程以了解服務器端的想法:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.