asp.net - 上传的文件未显示在 asp.net web api 控制器中
问题描述
我正在尝试构建简单的图像上传程序,但它不能按如下方式运行我的代码。如果有人能弄清楚这对我来说将是救命的谢谢
这是我的角度服务
postFiles(caption: string, filetouplaod: File) {
const headerss = new HttpHeaders({
'Content-Type': 'multipart/form-data',
'Authorization': this.globalsr.PrimaryTocken
})
let file: File = filetouplaod;
let formData: FormData = new FormData();
formData.append('uploadFile', file, file.name);
return this._http.post(`${this.globalsr.PrimaryAPI}Uploader/UploadSingleImage`, formData, {headers:headerss})
}
身份验证令牌
private _primaryTocken: string = "Bearer ansKFMPonKyab-TBmgQAThXNKoSAt8ZHej31-Is1a0X0wo5iSIjiaXvRdHscyr9J3v3iG3PTg8_BnoZaiMRCEY03zAONYrKppp1ZdSAgGenMcqeW-UYyKKkOEk7UhXO3l1_-9kXc9rBnekuOIqCrH8TfbcF_G_hgUVFS2N8omQYetJ-VobtaW8n-8AZL72wigGeckLtjZhm12aEEwxsDxnrrY4WA0kB3T9eNURvSO_9lwjJ2_oBRwOPojcAh-dfrlOln0DkSpYL8F2Si2Od63pesFnMZ9uhBkYjZvWCfeN0k8-V7jvBLae_Pz_ljoYM1rVRF-CXwQgBOKiKmSi9h65DUAsqaQY8gLXb69xqPmomscXLn4yVwsdkNyZlayuVlL3EhQgjslgss6xqiUw36SPSsfTN9rMmRQr3dpiJogn61U7kF5FqCRAhmjj_JPOo8aXoh1EGkov0ArerB6lgMDvt3UM_f8-Dzi0i8vtZrstg" ;
我的 Web api 控制器
[Authorize]
[HttpPost]
[Route("UploadSingleImage")]
public HttpResponseMessage UploadSingleImage()
{
var exMessage = string.Empty;
try
{
string uploadPath = "~/content/upload";
HttpPostedFile file = null;
if (HttpContext.Current.Request.Files.Count > 0)
{
file = HttpContext.Current.Request.Files.Get("file");
}
// Check if we have a file
if (null == file)
return Request.CreateResponse(HttpStatusCode.BadRequest, new
{
error = true,
message = "Image file not found"
});
// Make sure the file has content
if (!(file.ContentLength > 0))
return Request.CreateResponse(HttpStatusCode.BadRequest, new
{
error = true,
message = "Image file not found"
});
if (!Directory.Exists(HttpContext.Current.Server.MapPath(uploadPath)))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(HttpContext.Current.Server.MapPath(uploadPath));
}
//Upload File
file.SaveAs(HttpContext.Current.Server.MapPath($"{uploadPath}/{file.FileName}"));
}
catch (Exception ex)
{
exMessage = ex.Message;
}
return Request.CreateResponse(HttpStatusCode.BadRequest, new { error = true, message = exMessage == string.Empty ? "An unknown error occured" : exMessage });
}
但情况是这个文件计数一直为零。
HttpContext.Current.Request.Files.Count
所以我已经使用邮递员发送了确切的数据,并且 web api 方法工作正常。请有任何想法
解决方案
不要设置'Content-Type': 'multipart/form-data'
- 只需将其删除。一般来说,我删除Content-Type
了所有请求并将其替换为'Accept': 'application/json'
.
推荐阅读
- xamarin.forms - Xamarin 表单绑定 IEnumerable 本地化
- mysql - 如何在mysql中的多对多关系中获取单个ID
- java - Keyguard manager如何删除取消按钮
- javascript - Jquery 代码不适用于移动设备(Android)
- elasticsearch - Kibana 未在“发现”选项卡中显示结果
- python - 创建具有随机整数的 numpy 数组,每行具有另一个范围
- facebook-graph-api - Instagram API 弃用和切换到 Graph API
- logging - nlog .netcore 关闭 microsoft INFO 级别的日志记录
- php - 在sql php中自动生成id
- apache - 来自 RewriteCond 和 RewriteRule 的 htaccess 模式匹配