繁体   English   中英

如何异步上传.NET核心web API中的Word文件并保存到文件夹中

[英]How to upload Word file in .NET core web API asynchronously and save into a folder

我已经编写了用于在 .net 核心 web api 中上传 word 文件的代码,该文件异步工作正常,但由于此过程需要时间,因此用户不想更改文件的成功消息只会出现一次等待文件上传并返回“此过程需要一些时间”的消息,并且应该在后台进行文件上传。它不应因文件上传而阻止用户进行其他操作。

下面我提到了我尝试异步处理文件上传但它不起作用的代码。

html 和 Javascript 代码-

 <button id="fake-file-button-browse" type="button" class="btn btn-default" style="width:38px;height:34px;display:none"></button>
<input type="text" id="fileurl-name" style="width:50%;display:none" placeholder="File not selected" class="form-control">
<input class="Uploader" type="file" id="fileurl">

C# 代码,在 Web API Controller

public async Task<ActionResult> UploadAndConvertFile()
{

    try
    {
       
            List<string> listValues = new List<string>();
            foreach (string key in Request.Form.Keys)
            {
                listValues.Add(Request.Form[key]);
            }

            List<string> details = new List<string>()
            {
                listValues[0],listValues[2],listValues[5]
            };
            _response = _iOperation.GetAllFiles(details, CustomerId, "Legal Team");

            if (_response.ResponseContent != "Already Exist" && _response.StatusCode != 500)
            {
                Operation.UploadedFileDetails uploadedFileDetails = new Operation.UploadedFileDetails();

                uploadedFileDetails.CustomFileName = listValues[0];
                uploadedFileDetails.FileDescriptions = listValues[1];
                uploadedFileDetails.FileCategory = listValues[2];
                uploadedFileDetails.IsActive = !Convert.ToBoolean(listValues[3]);
                uploadedFileDetails.FileID = Convert.ToInt32(listValues[5]);
                
                    
                    Microsoft.AspNetCore.Http.IFormFile file = Request.Form.Files[0];
                    System.Threading.Tasks.Task.Run(() => UploadFile(uploadedFileDetails,file));
                    
                    _response.StatusCode = 200;
                    _response.ResponseContent = "File Upload will take some time.Please come after sometime.";
                    return StatusCode(Convert.ToInt16(_response.StatusCode), _response.ResponseContent);



                
                

            }

    } catch (Exception ex)
        {
            connection.fnHandleConnectionError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString(), connection.ConnectionString);
        }
        return StatusCode(Convert.ToInt16(_response.StatusCode), _response.ResponseContent);
    }

    public async Task<Library.APIResponse> UploadFile(UploadedFileDetails uploadedFileDetails, Microsoft.AspNetCore.Http.IFormFile File)
    {
        
        var file = File;
        object documentFormat = 8;
        string randomName = DateTime.Now.Ticks.ToString();
        string folderName = "Uploads\\";
        string webRootPath = _hostingEnvironment.WebRootPath;
        string combinedPath = Path.Combine(webRootPath, folderName);
        object htmlFilePath = combinedPath + randomName + ".htm";
        string directoryPath = combinedPath + randomName + "_files";
        string fileSavePath = combinedPath + Path.GetFileName(file.FileName);
        object fileSavePath1 = combinedPath + Path.GetFileName(file.FileName);
        //If Directory not present, create it.
        if (!Directory.Exists(combinedPath))
        {
            Directory.CreateDirectory(combinedPath);
        }
        _Application applicationclass = new Application();
        //Upload the word document and save to Uploads folder.

        try
        {
            if (file.Length > 0)
            {
                
                var filePath = Path.GetTempFileName();

                using (var stream = System.IO.File.Create(filePath))
                {
                    await file.CopyToAsync(stream);
                }
               
            }
            //Open the word document in background.
            applicationclass.Documents.Open(ref fileSavePath1);
            applicationclass.Visible = false;
            Document document = applicationclass.ActiveDocument;
            try
            {
                //Save the word document as HTML file.
                document.SaveAs(ref htmlFilePath, ref documentFormat);

                //close the document
                document.Close();
            }
            catch (Exception)
            {
                document.Close();
                throw;
            }

            //close the application
            applicationclass.Quit();
        }
        catch (Exception ex)
        {
            applicationclass.Quit();
            connection.fnHandleConnectionError(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.FullName.ToString() + "." + System.Reflection.MethodBase.GetCurrentMethod().Name.ToString(), ex.ToString(), connection.ConnectionString);
            throw;
        }
        //Read the saved Html File.
        string wordHTML =await System.IO.File.ReadAllTextAsync(htmlFilePath.ToString(), Encoding.Default);

        //Replace Image path
        wordHTML = wordHTML.Replace("src=\"", "src=\"Uploads/");

        //Delete the Uploaded Word File.
        System.IO.File.Delete(fileSavePath.ToString());

        uploadedFileDetails.DocFileName = file.FileName;
        uploadedFileDetails.HTMLFileName = randomName + ".htm";
        uploadedFileDetails.FileLocation = combinedPath;
        _response = await _iOperation.LogFileDetailsToDB(uploadedFileDetails); //This code to log to database the record

    return _response;
}

首先调用 UploadAndConvertFile 方法,该方法内部调用 UploadFile 方法,所以首先它应该返回消息“这个文件上传需要一些时间。”,然后在后台它应该调用 UploadFile 方法。

它正在调用 UploadFile 方法但何时到达
await file.CopyToAsync(stream); 这一行将捕获块并抛出错误“无法访问已处理的 object。Object 名称:'FileBufferingReadStream'。”

提前致谢。

尝试这个:

在 Web API Controller

[HttpPost]
[DisableRequestSizeLimit]
public async Task<IActionResult> UploadFile()
{
        try
        {
            var file = Request.Form.Files[0];
            var path = "D:/WordFiles/";
            if (file.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var fullPath = Path.Combine(path, fileName);
                using (var stream = new FileStream(fullPath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                return Ok();
            }
            else
            {
                return BadRequest();
            }
        }
        catch (Exception ex)
        {
            return return StatusCode(500, ex.Message);
        }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM