How can I pass parameters and uploading image at the same time to One web api?
Asked Answered
H

1

6

I use this controller:

 public class uploadphotosController : ApiController
    {
        public Task<HttpResponseMessage> Post( )
        {

            // Check if the request contains multipart/form-data.
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            string root =HostingEnvironment.MapPath("~/photos");//Burdaki app data klasoru degisecek
            var provider = new MultipartFormDataStreamProvider(root);

            // Read the form data and return an async task.
            var task = Request.Content.ReadAsMultipartAsync(provider).
                ContinueWith<HttpResponseMessage>(t =>
                {
                    if (t.IsFaulted || t.IsCanceled)
                    {
                        return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                    }

                    // This illustrates how to get the file names.
                    foreach (MultipartFileData file in provider.FileData)
                    {

                        string fileName = file.LocalFileName;
                        string originalName = file.Headers.ContentDisposition.FileName;


                        FileInfo file2 = new FileInfo(fileName);
                        file2.CopyTo(Path.Combine(root, originalName.TrimStart('"').TrimEnd('"')), true);
                        file2.Delete();

                        //Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                        // Trace.WriteLine("Server file path: " + file.LocalFileName);
                    }
                    return Request.CreateResponse(HttpStatusCode.OK);
                });


            return task;
        }

    }

And I use this in WebApiConfig.cs

   config.Routes.MapHttpRoute(
             name: "DefaultApi_uploadphotos",
             routeTemplate: "api/{ext}/uploadphotos/",
             defaults: new
             {
                 controller = "uploadphotos"
             });

It works fine, but I need to upload image with send email and password at the same time. Because I want to upload image if a user is exists. In my way everyone uploads photo as a user or not. I want to send image and some parameters like email and passwords to the same web api.

How can I do that?

thanks in advance

Hoar answered 15/12, 2014 at 13:57 Comment(4)
you should be able to use query parameters ?email=email&password=pw and then you should use HTTPS since you're passing passwords in clear text (at least I presume)Grammer
I cant understand , please give a sample ?Hoar
your Post can take parameters Post(string email, string pw) then you can access those in your body, post to url with query params like so http://yoursite.com/uploadphotos?email=whatever&pw=b4df00d and the image attachmentsGrammer
so public Task<HttpResponseMessage> Post( ) should be Post(String email,String password) ?Hoar
U
3

What worked for me:

public async Task<HttpResponseMessage> PostFile(string a, string b)
{
     var requestStream = await Request.Content.ReadAsStreamAsync();
  ...
}

Routing:

config.Routes.MapHttpRoute(
    name: "ControllerApi",
    routeTemplate: "/{controller}/{a}/{b}"
);

Sending file:

var request = (HttpWebRequest) HttpWebRequest.Create("http://host/controller/hello/world");
request.Method = "POST";
var stream = request.GetRequestStream();
var docFile = File.OpenRead(sourceFile);
docFile.CopyTo(stream);
docFile.Close();
stream.Close();
var response = request.GetResponse();
Unhandled answered 15/12, 2014 at 14:12 Comment(8)
what is var requestStream ? how can I reach parameters in web api sideHoar
It should be Task<HttpResponseMessage> PostFile(...) or I can be Task<HttpResponseMessage> Post(...) ?Hoar
I try it and It gives this error 404 not found (conn.getResponseMessage())Hoar
"hello" will be stored in string a and "world" will be stored in string b. You can just use Post or PostXY. requestStream is the Stream of your file.Unhandled
regarding 404: did you set the right value for host/controller ?Unhandled
I set it like this public Task<HttpResponseMessage> Post(string email, string password) but when I upload photo it gives that errorHoar
I use android to send image and at the same time 2 parametersHoar
Well I don't know why isn't working with your code :-) is the route correct? Is the post url correct? maybe it helps if you first try to send a file from a .net console app and then translate that bit to "android".Unhandled

© 2022 - 2024 — McMap. All rights reserved.