将文件上传到 ASP.NET Core 中不同服务器上 wwwroot 之外的文件夹

Posted

技术标签:

【中文标题】将文件上传到 ASP.NET Core 中不同服务器上 wwwroot 之外的文件夹【英文标题】:Upload a file to a folder outside wwwroot at a different server in ASP.NET Core 【发布时间】:2022-01-22 08:10:22 【问题描述】:

我正在尝试将文件上传到位于 ASP.NET Core 项目的托管服务器之外的文件夹。我尝试了不同的方法,但到目前为止都没有奏效。我也尝试使用 fttp 上传,但服务器提供商不允许这样做。这是我的代码

        public async Task<IActionResult> DevicePhotoGalary(int id, IFormFile file) // IFormFile for one Photo and IFormCollection for Multi Photo
        
            var QuestionObj = await _questionRepo.GetQuestionById(id);
            if (QuestionObj == null)
                return NotFound();

            var uploadFolderPath = Path.Combine(_webHostEnvironment.WebRootPath, "IQ Questions"); //location must be changed here

            if (!Directory.Exists(uploadFolderPath))
                Directory.CreateDirectory(uploadFolderPath);

            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
          

            var filePath = Path.Combine(uploadFolderPath, fileName);
            // var filePath = uploadFolderPath + fileName;
            using (var stream = new FileStream(filePath, FileMode.Create))
            
                file.CopyTo(stream);
            

            QuestionObj.Image =  fileName;
            await _questionRepo.UpdateQuestion(QuestionObj);

            return Ok(); 

非常感谢任何帮助。谢谢

【问题讨论】:

我使用“AppContext.BaseDirectory”。在我的服务器上,它是 wwwroot 的父级。 (Inetpub) 如果我的回复有帮助,请采纳为答案(点击回复旁边的标记选项将其从灰色切换为填写。),请参阅meta.stackexchange.com/questions/5234/… 【参考方案1】:

如果您不能在您的服务器中使用 FTP。最简单的方法是在需要上传文件的服务器上部署一个简单的web程序,程序包含上传接口。

然后就可以在DevicePhotoGalary方法中调用接口了。

如下代码


public IActionResult DevicePhotoGalary( IFormFile file) 

    var uploadFolderPath = Path.Combine(_webHostEnvironment.ContentRootPath, "IQ Questions"); //location must be changed here

    if (!Directory.Exists(uploadFolderPath))
        Directory.CreateDirectory(uploadFolderPath);

    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);


    var filePath = Path.Combine(uploadFolderPath, fileName);
    // var filePath = uploadFolderPath + fileName;
    using (var stream = new FileStream(filePath, FileMode.Create))
    
        // Invoke api in the server which will save the content
        //file.CopyTo(stream);
    

    return Ok();

【讨论】:

这是个好主意。让我试试并更新你。谢谢

以上是关于将文件上传到 ASP.NET Core 中不同服务器上 wwwroot 之外的文件夹的主要内容,如果未能解决你的问题,请参考以下文章

使用 Asp.NET Core 3.1 框架将文件上传到服务器时如何使用 IFormFile 作为属性?

使用 axios 从 vue 上传 XML 文件到 asp .net core

asp.net core 上传文件服务器拒绝是为啥?

上传图片 asp.net Core

在 ASP.NET Core 中上传文件

与 v11 相比,使用 v12 将文件上传到 Azure Blob 存储 SDK 的 ASP.NET Core 使用更高的内存