gpt4 book ai didi

c# - 如何从 asp.net-webpages 中的 Ajax 请求获取服务器端的已发布文件?

转载 作者:行者123 更新时间:2023-11-30 17:02:53 26 4
gpt4 key购买 nike

使用我在这里找到的有用信息:

How can I upload files asynchronously?

我能够使用以下 jQuery(从上面的链接稍作修改)将表单数据发送到服务器端:

$('#addFileInput').change(function () {
var file = this.files[0];
name = file.name;
size = file.size;
type = file.type;
//Your validation
});

$('.submitFile').click(function () {
var formData = new FormData($("#fileUploadForm"));
$.ajax({
url: '/AJAX Pages/Compute_File_Upload.cshtml', //Server script to process data
type: 'POST',
xhr: function () { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
if (myXhr.upload) { // Check if upload property exists
myXhr.upload.addEventListener('progress', progressHandlingFunction, false); // For handling the progress of the upload
}
return myXhr;
},
//Ajax events
beforeSend: function () {
$("#progressBar").css("visibility", "visible");
},
success: function (response) {
$(".editLabelTitle").text(response);
},
//error: errorHandler,
// Form data
data: formData,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false
});
});

function progressHandlingFunction(e) {
if (e.lengthComputable) {
$('progress').attr({ value: e.loaded, max: e.total });
}
}

这是涉及的 HTML:

<div class=\"addFileBox\">
<div class=\"editPageSubTitle dragHandle\">
Add File
<button id=\"closeAddFileBox\">X</button>
</div>
<div class=\"innerAddFileDiv\">
<form id=\"fileUploadForm\" enctype=\"multipart/form-data\">
<input id=\"addFileInput\" name=\"addFileInput\" type=\"file\" />
</form>
<br/>
<progress id=\"progressBar\"></progress>
<br/>
<button class=\"submitFile\">Submit File</button>
</div>
</div>

Ajax 请求本身工作正常。当我不知道如何在服务器端代码上获取文件时,问题就来了(通常我只会用 Request.Files["someFileId"]) 找到输入,但作为所有 formData已发送,这不是我熟悉的方式。

C# 代码隐藏

@{
Layout = "";

if(IsAjax)
{
var file = Request.Files["addFileInput"];

var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/CMS Files/UtilityBilling"), fileName);
file.SaveAs(path);
}

考虑到我的场景和环境,访问给定文件的正确方法是什么?

最佳答案

从代码隐藏试试这个:

        HttpFileCollection filesCollection = HttpContext.Current.Request.Files;
var fileName = filesCollection[0];
string filePath = Path.Combine(HttpContext.Current.Server.MapPath("~/SaveDir"), fileName.FileName);
fileName.SaveAs(filePath);

关于c# - 如何从 asp.net-webpages 中的 Ajax 请求获取服务器端的已发布文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19280455/

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