【发布时间】:2017-04-10 17:28:08
【问题描述】:
我已经阅读了一些相关的帖子,但到目前为止任何人都可以帮助我,我现在正在尝试上传在客户端的输入文件中选择的文件,然后使用 jquery ajax 调用调用服务器方法,请问我如何正在做:
服务器端方法:
[WebMethod]public static void UploadDetailImageFromClient(string filename, string caption, string itemid, string inspid) {
HttpPostedFile file = HttpContext.Current.Request.Files["ContentPlaceHolder1_uploadBtn"]; if (file != null && file.ContentLength > 0) //See the id here include ContentPlaceHolder as I'm using a MasterPage, here is where I'm never getting the file, it comes NULL
{
string fname = Path.GetFileName(file.FileName);
if (!System.IO.File.Exists(Path.Combine("images/", fname))) {
file.SaveAs(HttpContext.Current.Server.MapPath(Path.Combine("images/", fname)));
}
}
}
客户端:
<td><asp:FileUpload ID="uploadBtn" runat="server" accept=".png,.jpg,.jpeg,.gif"/></td>
这是我调用服务器方法的函数:
function uploadnewpicture() {
jQuery.ajax({
type: "POST",
url: "FormInspectionsMidPoint.aspx/UploadDetailImageFromClient",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ filename: filename, caption: caption, itemid: itemid, inspid: inspid }),
dataType: "json",
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
},
success: function (data) {
jQuery("#ContentPlaceHolder1_uploadBtn").val("");
jQuery("#ContentPlaceHolder1_txtImageDetailCaption").val("");
alert("Picture uploaded successfully");
}
});
}
请注意,我是从 jQuery 对话框内的 click 事件上的输入按钮调用此 javascript 函数。这就是为什么我使用 ajax 调用来保持对话框打开以及从客户端读取输入文件中的值。我也在表单中使用 enctype="multipart/form-data"。
我希望有人有同样的情况并可以帮助我。谢谢。
【问题讨论】:
-
自从我使用 Web 表单和相关控件多年以来,请原谅我。 JS开火了吗?浏览器中的任何错误(萤火虫)?您是在本地调试并单步执行服务器端的流程吗?
-
调用该方法没有错误,该方法运行良好,正如我所说,我现在唯一的问题是这一行:HttpPostedFile file = HttpContext.Current.Request.Files["ContentPlaceHolder1_uploadBtn"];该文件始终为空。
-
作为 Request.Files 返回一个集合;验证计数是否为 1,然后尝试仅使用第一个索引 ( Request.Files[0] ) 并查看传入的内容。firebug(或其他浏览器检查器)显示正在发送什么?
-
是的,我也试过了: HttpFileCollection filesCollection = HttpContext.Current.Request.Files; var fileName = filesCollection[0];但是集合为空(0)。