0

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

frido
  • 13,065
  • 5
  • 42
  • 56
  • Server.MapPath gives the path according to the local filesystem of the server - this is probably not a publicly accessible path. Plus if that file is being uploaded, it probably doesn't exist yet – Hans Kesting Aug 07 '19 at 08:40
  • 1
    The error is reported by a `controllers/Api_projects.php` of which we know nothing – Hans Kesting Aug 07 '19 at 08:41

2 Answers2

0

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

Andrei Tătar
  • 7,872
  • 19
  • 37
0

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

golobitch
  • 1,466
  • 3
  • 19
  • 38