在ASP.NET Web API控制器中未显示上载的文件

时间:2019-02-09 05:42:40

标签: asp.net angular

我正在尝试构建简单的图像上传程序,但无法正常工作 我的代码如下。如果有人能弄清楚,这将为我挽救生命 谢谢

这是我的角度服务

 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})
}

身份验证令牌

私人_primaryTocken:字符串= “承载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

所以我已经使用邮差和网络api方法发送了准确的数据。 任何想法

2 个答案:

答案 0 :(得分:0)

file无法从文件输入元素中获取您要上传的文件。使用控制台日志检查filetouplaod的内容。

 let file: File = filetouplaod;

假设fileInput是输入元素,那么您应该分配类似filetouplaod = fileInput.files[0]

答案 1 :(得分:0)

不设置'Content-Type': 'multipart/form-data'-删除即可。 一般说来,我在所有请求中都删除了Content-Type并替换为'Accept': 'application/json'