gpt4 book ai didi

c# - 使用 jQuery AJAX 和处理程序 (ashx) 上传文件不起作用

转载 作者:太空狗 更新时间:2023-10-30 00:25:31 24 4
gpt4 key购买 nike

我正在尝试使用 jQuery AJAX 和通用处理程序上传图像文件。但似乎文件没有传递给处理程序。提交后 context.Request.Files[0]; 始终为 null :-/

我做错了什么?

HTML:

<form id="form1" runat="server" method="post" enctype="multipart/form-data">

<input name="file" id="file" type="file" />
<input id="save" name="submit" value="Submit" type="submit" />

</form>

JS:

$().ready(function ()
{
$('#file').change(function ()
{
sendFile(this.files[0]);
});
});

function sendFile(file)
{
$.ajax({
type: 'post',
url: 'FileUpload.ashx',
data: file,
success: function () {
// do something
},
xhrFields:
{
onprogress: function (progress)
{
// calculate upload progress
var percentage = Math.floor((progress.total / progress.totalSize) * 100);

// log upload progress to console
console.log('progress', percentage);

if (percentage === 100) {
console.log('DONE!');
}
}
},
processData: false,
contentType: 'multipart/form-data'
});
}

阿什克斯:

public void ProcessRequest (HttpContext context) 
{
HttpPostedFile file = context.Request.Files[0];

if (file.ContentLength > 0)
{
//do something
}
}

最佳答案

设法让这个工作 :)

这是我的代码...

///create a new FormData object
var formData = new FormData(); //var formData = new FormData($('form')[0]);

///get the file and append it to the FormData object
formData.append('file', $('#file')[0].files[0]);

///AJAX request
$.ajax(
{
///server script to process data
url: "fileupload.ashx", //web service
type: 'POST',
complete: function ()
{
//on complete event
},
progress: function (evt)
{
//progress event
},
///Ajax events
beforeSend: function (e) {
//before event
},
success: function (e) {
//success event
},
error: function (e) {
//errorHandler
},
///Form data
data: formData,
///Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false,
processData: false
});
///end AJAX request

关于c# - 使用 jQuery AJAX 和处理程序 (ashx) 上传文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16963787/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com