我正在尝试使用ajax上传图片。我发送的请求是这样的:
@using (Ajax.BeginForm("SaveReferral", "ReferralIM", new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccessReferralSent"
}, new { id = "frmReferral", onSubmit = "OnControlMapping(this);" }))
{
}
如果我发送这样的请求:
@using (Html.BeginForm("SaveReferral", "ReferralIM", FormMethod.Post, new { id = "frmReferral", enctype = "multipart/form-data" }))
{
文件上传成功,但我想使用ajax,请帮我如何使用ajax上传文件。 感谢
答案 0 :(得分:0)
如果您想使用$ .ajax,我不使用MVC BUT,那么它就是......
$('.file-uploadID').on('click', function (e) {
e.preventDefault();
var fileInput = $('.file-uploadID');
var fileData = fileInput.prop("files")[0]; // Getting the properties of file from file field
formData.append("file", fileData); // Appending parameter named file with properties of file_field to form_data
formData.append("user_email", email); //adding email address as parameter if you have
$.ajax({
url: '/FileUploadHandler.ashx',
data: formData,
processData: formData.processData,
contentType: formData.contentType,
type: 'POST',
success: function (data) {
var obj = $.parseJSON(data);
if (obj.StatusCode == "OK") {
alert("file upload done");
} else if (obj.StatusCode == "ERROR") {
alert("file upload error");
}
},
error: function (errorData) {
$('.result-message').html("There was a problem uploading the file. Please try again.").show();
}
});
});
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Expires = -1;
var email = context.Request.Params["user_email"];
var fileData = context.Request.Files["file"];
try
{
var result = UploadImageToServer(email, fileData);
context.Response.Write(result);
}
catch (Exception ex)
{
context.Response.Write("error while uploading file to the server, please try again.");
}
}