gpt4 book ai didi

javascript - 将文件对象从 Javascript 传递到 Web API

转载 作者:行者123 更新时间:2023-12-02 15:25:13 24 4
gpt4 key购买 nike

我正在尝试通过 Javscript Web api 调用通过 Web api 将文件从本地计算机上传到共享点。尝试将文件对象从 javascript 传递到 Web api,但我不断收到类型错误、找不到资源等错误。任何人都可以提供帮助吗?

Javascript代码:

 $scope.Upload = function () {
if (!window.FileReader) {
alert("This browser does not support the HTML5 File APIs");
return;
}

var element = document.getElementById("uploadInput");
var file = element.files[0];
//var folderStructure = "/PublishingImages/Lists/Featured%20Stories/";
var parts = element.value.split("\\");
var fileName = parts[parts.length - 1];
filename1 = fileName;
var descriptionName = fileName;
var reader = new FileReader();
var indentifier = '';

//url = encodeURI(url);
reader.onload = function (e) {
UploadDocs(e.target.result, fileName);
}
reader.onerror = function (e) {
alert(e.target.error);
}
reader.readAsArrayBuffer(file);

}

function UploadDocs(str, file) {
var url = webApiUrl + "api/Registration/UploadFileToDocmentLibrary";
$.ajax({
type: "POST",
url: url,
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(str),
dataType: 'json',
async: false,

success: function (response) {
console.log(response.fileData);
console.log('Success');
},
error: function (data) {
console.log('fail');
}

});
}


Web API 代码:

[HttpPost] // This is from System.Web.Http, and not from System.Web.Mvc
public void UploadFileToDocmentLibrary(HttpPostedFile uploadFile)
{
//code to upload to sharepoint
}

最佳答案

您可以使用FormData上传整个文件

JS:

$scope.uploadDocs = function () {
var element = document.getElementById("uploadInput");
var file = element.files[0];

var loFormData = new FormData();
loFormData.append("filename", file.name);
loFormData.append("file", file);

var loAjaxRequest = $.ajax({
cache: false,
type: 'POST',
url: webApiUrl + "api/Registration/UploadFileToDocmentLibrary",
contentType: false,
processData: false,
data: loFormData
});

loAjaxRequest.done(function (xhr, textStatus) {
alert(textStatus);
});
};

Web-Api:

[HttpPost]
public async Task<HttpResponseMessage> UploadFileToDocmentLibrary()
{
if (!this.Request.Content.IsMimeMultipartContent())
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
try
{
var loProvider = new MultipartFormDataStreamProvider(Path.GetTempPath());

await Request.Content.ReadAsMultipartAsync(loProvider);

string lsFilename = loProvider.FormData.GetValues("filename").First();
var loFile = loProvider.FileData.First();
string lsFileContent = File.ReadAllText(loFile.LocalFileName);

return new HttpResponseMessage(HttpStatusCode.OK);
}
catch (Exception exp)
{
return this.Request.CreateErrorResponse(HttpStatusCode.InternalServerError, exp);
}
}

关于javascript - 将文件对象从 Javascript 传递到 Web API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33752036/

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