简体   繁体   English

在C#中使用Web Api上传文件

[英]Upload file using web Api in c#

I am trying to upload file using web api in c#. 我正在尝试使用C#中的Web API上传文件。 I tried in postman. 我试过邮递员。 It works properly. 它正常工作。 I was confuse how to do it in c# code . 我很困惑如何在c#代码中做到这一点。 I have tried following code but it gives error. 我试过下面的代码,但它给出了错误。

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

When run the code it write following error message on screen 运行代码时,它在屏幕上写以下错误消息

A PHP Error was encountered Severity: Notice Message: Undefined index: img 遇到PHP错误严重性:通知消息:未定义的索引:img
Filename: controllers/Api_projects.php 文件名:controllers / Api_projects.php
Line Number: 27 行号:27
Backtrace: 回溯:
File: /home/fpipj1blp4wo/public_html/ecosense.in/application/controllers/Api_projects.php Line: 27 Function: _error_handler 文件:/home/fpipj1blp4wo/public_html/ecosense.in/application/controllers/Api_projects.php行:27功能:_error_handler
File: /home/fpipj1blp4wo/public_html/ecosense.in/application/libraries/REST_Controller.php Line: 785 Function: call_user_func_array 文件:/home/fpipj1blp4wo/public_html/ecosense.in/application/libraries/REST_Controller.php行:785功能:call_user_func_array
File: /home/fpipj1blp4wo/public_html/ecosense.in/index.php Line: 315 Function: require_once 文件:/home/fpipj1blp4wo/public_html/ecosense.in/index.php行:315功能:require_once

plz help 请帮助

Sending multipart/form-data is a bit more complicated. 发送multipart/form-data要复杂一些。 Have a look at: Upload files with HTTPWebrequest (multipart/form-data) 看一下: 使用HTTPWebrequest(多部分/表单数据)上传文件

Since you didn't write what are you using (.NET Framework or .NET Core,...) I will assume that you mean .NET Core Web Api. 由于您没有编写使用的内容(.NET Framework或.NET Core,...),因此我假设您的意思是.NET Core Web Api。 So, I do this by creating folder (for instance Resources (this dir is in the same dir that is controllers, migrations, models,....), and inside Resource folders I create another folder called Images. 因此,我通过创建文件夹(例如,Resources(此目录与控制器,迁移,模型等相同的目录)来完成此操作,然后在Resource文件夹中创建另一个名为Images的文件夹。

Then in desired controller, I do this: 然后在所需的控制器中,我这样做:

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

This should work. 这应该工作。 However, this uploaded files/images, are stored in Resource folder, and we need to make this folder servable. 但是,此上载的文件/图像存储在Resource文件夹中,我们需要使该文件夹可用。 So you need to modify the Configure method in Startup.cs class 因此,您需要修改Startup.cs类中的Configure方法

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

This is just an example. 这只是一个例子。 There are many more ways to upload an image. 还有更多上传图片的方法。

Hope it helps 希望能帮助到你

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

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