我为我正在开发的项目创建了一个HttpHandler。处理程序从HTML表单接收图像。数据通过JQUERY / AJAX发送。我想知道我是否可以从同一个电话接收剩余的表单数据。在这个例子中,我有两个输入:文件选择器和文本框。我想在文本框中阅读最新内容。是否可以在提交表单时检索文本框数据,还是必须单独执行?
的javascript:
function sendFile(file) {
var formData = new FormData();
formData.append('file', $('#f_UploadImage')[0].files[0]);
$.ajax({
type: 'post',
url: 'fileUploader.ashx',
data: formData,
success: function (status) {
if (status != 'error') {
var my_path = "MediaUploader/" + status;
$("#myUploadedImg").attr("src", my_path);
}
},
processData: false,
contentType: false,
error: function () {
alert("Whoops something went wrong!");
}
});
}
ASP处理程序代码:
using System;
using System.Web;
using System.IO;
public class fileUploader : IHttpHandler {
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
string[] files;
int numFiles;
files = System.IO.Directory.GetFiles(dirFullPath);
numFiles = files.Length;
numFiles = numFiles + 1;
string str_image = "";
foreach (string s in context.Request.Files)
{
HttpPostedFile file = context.Request.Files[s];
string fileName = file.FileName;
string fileExtension = file.ContentType;
if (!string.IsNullOrEmpty(fileName))
{
fileExtension = Path.GetExtension(fileName);
str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
string pathToSave_100 = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
file.SaveAs(pathToSave_100);
}
}
// database record update logic here ()
context.Response.Write(str_image);
}
catch (Exception ac)
{
}
}
public bool IsReusable {
get {
return false;
}
}
}
HTML:
<input type="text" id=f_input>
<input type="file" class="upload" id="f_UploadImage">
答案 0 :(得分:0)
您可以一次获取所有表单数据并将其放入formData变量中。
var formData = new FormData($('form')[0]);
或者你可以像你已经开始那样单独追加你想要的每一位数据:
var formData = new FormData();
formData.append('file', $('#f_UploadImage')[0].files[0]);
formData.append('text', $('#f_input').val());
无论哪种方式,您都应该将所有表单数据提交给处理程序代码。
有时您必须调整ajax设置才能使图像和文本内容正确完成。下面是我目前用来提交带有图像的表单数据,然后是表单外的令牌。
var formData = new FormData($('form')[0]);
formData.append("__RequestVerificationToken", $('[name=__RequestVerificationToken]').val());
$.ajax({
url: "/URL",
type: 'POST',
contentType: false,
processData: false,
data: formData,
dataType: 'json',
success: function(data) {
//do stuff
}
});