Asp.net Core 2.0中的文件上传问题创建了0字节的图像 [英] File Upload in Asp.net core 2.0 issue creating 0 byte Image

查看:31
本文介绍了Asp.net Core 2.0中的文件上传问题创建了0字节的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有asp.net core 2.0的angular 5.我正在尝试将文件上传到服务器.该代码将文件更新到服务器.但是具有0 kb的数据,有时它会上传文件.

I, am using angular 5, with asp.net core 2.0. I, am trying to upload the file to the server. The code update the file to the server. But with 0 kb of data and sometime it upload the file.

文件大小不大.以KB为单位.

The file size is not large. Its in KB.

这里是Angular代码

Here is the Angular code

 public QuestionPostHttpCall(_questionPhotoVM: QuestionPhotoViewModel): Observable<GenericResponseObject<QuestionPhotoViewModel[]>> {
        const formData: FormData = new FormData();
        formData.append('FileUpload', _questionPhotoVM.FileUpload);
        formData.append('QuestionText', _questionPhotoVM.questionText);
        formData.append('QuestionId', _questionPhotoVM.questionId);
        const headers = new HttpHeaders().set('enctype', 'multipart/form-data');
        return this._httpClientModule.post<GenericResponseObject<QuestionPhotoViewModel[]>>(this.questionPhotoUrl, formData);
    }

在控制器I中,可以接收文件.

In the controller I, can receive the file.

这是控制器方法

[HttpPost]
public JsonResult QuestionPhotoPost(IFormFile FileUpload, string QuestionText, Guid? QuestionId)
{
    string TempFileName = string.Empty;
    var directiveToUpload = Path.Combine(_environment.WebRootPath, "images\\UploadFile");
    var http = HttpRequestExtensions.GetUri(Request);
    QuestionViewModel model = new QuestionViewModel();
    try
    {

        if (FileUpload != null)
        {
            TempFileName = FileUpload.FileName;
            CheckFileFromFrontEnd();
        }

    }
    catch (Exception exception)
    {

    }

    void CheckFileFromFrontEnd()
    {
        if (FileUpload != null)
        {
            if (!System.IO.Directory.Exists(directiveToUpload))
            {
                System.IO.Directory.CreateDirectory(directiveToUpload);
            }
            if (System.IO.File.Exists(string.Format("{0}\\{1}\\{2}", _environment.WebRootPath, "images\\UploadFile", FileUpload.FileName)))
            {
                TempFileName = Guid.NewGuid().ToString() + FileUpload.FileName;
            }
            model.PictureUrl = string.Format("{0}://{1}/{2}/{3}/{4}", http.Scheme, http.Authority, "images", "UploadFile", TempFileName);
            SaveFileToServer(TempFileName);
        }

    }


    void SaveFileToServer(string FileName)
    {

        if (FileUpload.Length > 0)
        {
            using (var stream = new FileStream(Path.Combine(directiveToUpload, FileName), FileMode.Create))
            {
                FileUpload.CopyToAsync(stream);
            }
        }

    }
    return Json(genericResponseObject);
}

文件已上传到服务器.但是有时它以0字节上传,有时又正确上传.

The file is uploaded to the server. But some time it upload with 0 byte and sometime it upload correctly.

文件分辨率为570 X 400,文件大小为197KB

The resolution of file is 570 X 400 and size of file 197KB

我在哪里做错了?请任何人让我知道.是的,我需要在某处指定最大字节??

Where I, am doing wrong?? Please anyone let me know. Do, I need to specify max byte in somewhere ??

推荐答案

您的问题是您使用的是异步函数,而不是 await .
您使用的是ASP.NET Core,因此您应该 (读为"must")必须使用异步所有模式:

Your problem is that you are using an asynchronous function and not awaiting it.
You are using ASP.NET Core so you should (read "must") use the async-all-the-way pattern:

[HttpPost]
public async Task<JsonResult> QuestionPhotoPost(IFormFile FileUpload, string QuestionText, Guid? QuestionId)
{
    string TempFileName = string.Empty;
    var directiveToUpload = Path.Combine(_environment.WebRootPath, "images\\UploadFile");
    var http = HttpRequestExtensions.GetUri(Request);
    QuestionViewModel model = new QuestionViewModel();
    try
    {

        if (FileUpload != null)
        {
            TempFileName = FileUpload.FileName;
            await CheckFileFromFrontEndAsync();
        }

    }
    catch (Exception exception)
    {

    }

    async Task CheckFileFromFrontEndsync()
    {
        if (FileUpload != null)
        {
            if (!System.IO.Directory.Exists(directiveToUpload))
            {
                System.IO.Directory.CreateDirectory(directiveToUpload);
            }
            if (System.IO.File.Exists(string.Format("{0}\\{1}\\{2}", _environment.WebRootPath, "images\\UploadFile", FileUpload.FileName)))
            {
                TempFileName = Guid.NewGuid().ToString() + FileUpload.FileName;
            }
            model.PictureUrl = string.Format("{0}://{1}/{2}/{3}/{4}", http.Scheme, http.Authority, "images", "UploadFile", TempFileName);
            await SaveFileToServerAsync(TempFileName);
        }

    }

    async Task SaveFileToServerAsync(string FileName)
    {
        if (FileUpload.Length > 0)
        {
            using (var stream = new FileStream(Path.Combine(directiveToUpload, FileName), FileMode.Create))
            {
                await FileUpload.CopyToAsync(stream);
            }
        }
    }

    return Json(genericResponseObject);
}

为使代码更具可读性,我将这些内联函数移至外部.

To make the code more readable, I'd move those inline functions to outside, though.

这篇关于Asp.net Core 2.0中的文件上传问题创建了0字节的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆