提问者:小点点

在c#中使用web Api上传文件


我正在尝试使用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
文件名:控制器/Api_projects.php
行号:27
回溯:
文件: /home/fpipj1blp4wo/public_html/ecosense.in/application/controllers/Api_projects.php行:27函数:_error_handler
文件:/首页/fpij1blp4wo/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

plz帮助


共2个答案

匿名用户

发送多部分/表单数据有点复杂。查看:使用HTTPWebrequest上载文件(多部分/表单数据)

匿名用户

由于您没有编写您正在使用的内容(.NET Framework或.NET Core,…)我想你是说。NET核心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");
    }
}

这应该行得通。但是,此上传的文件/图像存储在资源文件夹中,我们需要使此文件夹可维护。所以你需要在S类中修改配置方法tartup.cs

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

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

希望有帮助