简体   繁体   中英

Upload file using web Api in c#

I am trying to upload file using web api in c#. I tried in postman. It works properly. I was confuse how to do it in c# code . 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
Filename: controllers/Api_projects.php
Line Number: 27
Backtrace:
File: /home/fpipj1blp4wo/public_html/ecosense.in/application/controllers/Api_projects.php Line: 27 Function: _error_handler
File: /home/fpipj1blp4wo/public_html/ecosense.in/application/libraries/REST_Controller.php Line: 785 Function: call_user_func_array
File: /home/fpipj1blp4wo/public_html/ecosense.in/index.php Line: 315 Function: require_once

plz help

Sending multipart/form-data is a bit more complicated. Have a look at: Upload files with HTTPWebrequest (multipart/form-data)

Since you didn't write what are you using (.NET Framework or .NET Core,...) I will assume that you mean .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.

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. So you need to modify the Configure method in Startup.cs class

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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