【问题标题】:Upload file using web Api in c#在 c# 中使用 web Api 上传文件
【发布时间】:2019-12-14 20:10:44
【问题描述】:

我正在尝试在 c# 中使用 web api 上传文件。我试过邮递员。它工作正常。我很困惑如何在 c# 代码中做到这一点。 我尝试了以下代码,但它给出了错误。

var request = (HttpWebRequest)WebRequest.Create("http://Api_projects/add_project");
var postData = "name=thisIsDemoName&img=" + Server.MapPath(FileUpload1.FileName) +"&info=ThisIsDemoInfo";
var data = Encoding.ASCII.GetBytes(postData);
request.Method = "POST";
request.ContentType = "multipart/form-data";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
    stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
Response.Write(responseString);

当运行代码时,它会在屏幕上显示以下错误消息

遇到 PHP 错误 严重性:通知 消息:未定义索引:img
文件名:controllers/Api_projects.php
行号:27
回溯:
文件:/home/fpipj1blp4wo/public_html/ecosense.in/application/controllers/Api_projects.php 线路:27 函数:_error_handler
文件:/home/fpipj1blp4wo/public_html/ecosense.in/application/libraries/REST_Controller.php 线路:785 函数:call_user_func_array
文件:/home/fpipj1blp4wo/public_html/ecosense.in/index.php 线路:315 函数:require_once

请帮忙

【问题讨论】:

  • Server.MapPath 根据服务器的本地文件系统给出路径 - 这可能不是可公开访问的路径。另外,如果该文件正在上传,它可能还不存在
  • 这个错误是由我们一无所知的controllers/Api_projects.php报告的

标签: c# php


【解决方案1】:

发送multipart/form-data 有点复杂。看看:Upload files with HTTPWebrequest (multipart/form-data)

【讨论】:

    【解决方案2】:

    由于您没有写出您使用的是什么(.NET Framework 或 .NET Core,...),我假设您的意思是 .NET Core Web Api。 因此,我通过创建文件夹(例如资源(此目录与控制器、迁移、模型等在同一个目录中)来做到这一点,并在资源文件夹中创建另一个名为 Images 的文件夹。

    然后在所需的控制器中,我这样做:

    [HttpPost]
    public IActionResult Upload() {
        try {
            var file = Request.Form.Files[0];
            var folderName = Path.Combine("Resources", "Images");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
    
            if (file.Length > 0) {
                var fname = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
                var fullPath = Path.Combine(pathToSave, fname);
                var dbPath = Path.Combine(folderName, fileName);
    
                using (var stream = new FileStream(fullPath, FileMode.Create)) {
                    file.CopyTo(dbPath);
                }
    
                return Ok(new { dbPath });
            }
            else {
                return BadRequest();
            }
        }
        catch (Exception ex) {
            return StatusCode(500, "Internal server error");
        }
    }
    

    这应该可行。但是,这个上传的文件/图像存储在 Resource 文件夹中,我们需要使这个文件夹可服务。所以需要修改 Startup.cs 类中的 Configure 方法

    app.UseStaticFiles();
    app.UseStaticFiles(new StaticFileOptions() {
        FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), @"Resources")),
            RequestPath = new PathString("/Resources")
    });
    

    这只是一个例子。还有很多上传图片的方法。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-10-25
      • 2017-12-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 2012-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多