File Upload in Asp.net core 2.0 issue creating 0 byte Image

不想你离开。 提交于 2021-02-20 04:23:45

问题


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.

The file size is not large. Its in KB.

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

In the controller I, can receive the file.

Here is the controller method

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

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

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 ??


回答1:


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.



来源:https://stackoverflow.com/questions/48866710/file-upload-in-asp-net-core-2-0-issue-creating-0-byte-image

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!