0

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 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

2 Comments

You forgot to await the very same thing OP originally did not await :)
@Evk Oops, you are right. I originally only fixed SaveFileToServerAsync and then decided to change everything and forgot that one. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.