How to upload image using rest web services in symfony - web-services

I am trying upload image using rest web service in my symfony application. I have tried the following code but it is throwing the error undefined index photo. I want to know what is the right way to do it.
I have followed how to send / get files via web-services in php but it didn't worked.
Here is the my html file with which am hitting the application url:
<form action="http://localhost/superbApp/web/app_dev.php/upload" enctype='multipart/form-data' method="POST">
<input type="file" name="photo" ></br>
<input type="submit" name="submit" value="Upload">
</form>
And my controller method is like:
public function uploadAction(){
$request = $this->getRequest(); /*** get the request method ****/
$RequestMethod = $request->getMethod();
$uploads_dir = '/uploads';
foreach ($_FILES["photo"]["error"] as $key => $error) {
if ($error == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["photo"]["tmp_name"][$key];
$name = $_FILES["photo"]["name"][$key];
move_uploaded_file($tmp_name, $uploads_dir."/".$name);
}
}
}

If you are using Symfony, you should use Symfony forms to do this. In your example, you put an URL which is pointing to app_dev.php, but that url doesn't work in production mode. In the Symfony cookbook there is an article explaining how upload files, which you should read:
http://symfony.com/doc/current/cookbook/doctrine/file_uploads.html
When you have done this, you can upload images via Rest WebService using the route specified for your action, specifying the Content-Type to multipart/form-data, and the name of the field which you add the image would be something like this package_yourbundle_yourformtype[file].

Related

Asp.net core passing multiple parameter + web api

I am submitting a form that passes three values to the controller, which are email, fullname and id fields.
#using (Html.BeginForm("SubmitResult", "TestAPI", FormMethod.Post, new { id = "postEmailForm" }))
{
<div id="details-container">
<input type="text" name="email" />
<input type="text" name="fullName" />
<input type="text" name="studentId" />
<button type="submit" id="send">Send</button>
</div>
}
Controller:
[HttpPost("SubmitResult/{email}/{fullName}/{studentId}")]
[Authorize(Roles = "Admin, Shop")]
public IActionResult SubmitResult(string email, string fullName, long? studentId)
{
}
However, when I click on submit button, it throws an error message in the console.
OPTIONS https://localhost:50138/TestAPI/SubmitResult
net::ERR_SSL_PROTOCOL_ERROR.
Headers:
Request URL: https://localhost:50138/TestAPI/SubmitResult
Referrer Policy: no-referrer-when-downgrade
How do I properly decorate the attribute in the controller, so I can pass multiple parameters to test API using Postman?
I was expecting something like below to work for testing.
http://localhost:50138/api/TestAPI/SubmitResult/test#gmail.com/MikeShawn/2
There are few issues with your code.
First issue is that it looks like when you post the data it tries to send it using a cross-origin request. If this is on purpose then you have to add CORS middleware in your pipe. If not - you have to figure out why it happens and fix it. There are not enough details in your question to say why it happens.
Two URLs have the same origin if they have identical schemes, hosts, and ports.
Second issue is that you are trying to send data by adding parameters to URL. This is wrong because the data will be sent in the request body. So regarding HttpPost attribute it should look like this:
[HttpPost]
[Authorize(Roles = "Admin, Shop")]
public IActionResult SubmitResult(string email, string fullName, long? studentId)
{
}
UPDATE
Just looked at your question again. It seems the page with form itself was opened using http scheme, but the POST request is actually going to https scheme. So to resolve first issue make sure that page with form is loaded using https scheme too.

User redirect with POST in iframe

I am building one of my first MVC 4 applications and I need some help with redirecting users.
I have a windows form application where I use a AxSHDocVw.AxWebBrowser to redirect the user to a specific URL , a SOAP web service to be precise, aswell as sending HTTP POST and HEADER data aswell.
This is done like so:
oHeaders = "Content-Type: application/x-www-form-urlencoded" + "\n" + "\r";
sPostData = "ExchangeSessionID=" + SessionID;
oPostData = ASCIIEncoding.ASCII.GetBytes(sPostData);
axWebBrowser2.Navigate2(ref oURL, ref o, ref o, ref oPostData, ref oHeaders);
I am looking to replicate this functionality in my MVC application, but am unsure of the how this can be done.
I was hoping to have this within an iframe, but can't find a way of sending the POST and HEADER data from this. This is what I have been trying so far:
Controller
ViewBag.URL = TempData["URL"];
ViewBag.SessionID = TempData["SessionID"];
ViewBag.FullURL = TempData["URL"] + "?ExchangeSessionID=" + TempData["SessionID"];
return View();
View
<iframe src="#ViewBag.FullURL" width="100%" height="500px"></iframe>
Basically I was trying to append the data to the end of the URL hoping this would work for the HTTP POST part. This is what I ended up with:
https://www.myurl.aspx?ExchangeSessionID=87689797
The user is being directed to the page, but the web service is giving me an error ( which tells me it is now receiving the POST data).
Can some please help me to try and fix this, or even give me advice on how to go about this another way. Like I said, I'm fairly new to MVC applications and I'm not entirely sure what I'm tryin to do is even possible.
Any help is appreciated. Thanks
I've decided to answer this question myself incase anybody is looking to do something similar in the future.
The first step was to create my iframe:
<iframe name="myframe" src="" width="100%" height="700px"></iframe>
Next I want to create a form with a button which, when pressed, will post the data to the url while targeting the iFrame (Note the target attribute of the form):
<form action="#ViewBag.URL" method="post" target="myframe">
<input type="hidden" name="ExchangeSessionID" value="#ViewBag.SessionID" />
<input type="submit" value="Submit" />
</form>
So what happens is, when the button is pressed, the form posts the ExchangeSessionID to the target URL and then the page response is displayed inside the iFrame.

nopCommerce 2.40 Admin Product Edit Addition

Hopefully I can get some headway here as nopCommerce forums has been silent to my post. My current situation is that for each product we have in our store, we(admins) need to upload a specific document and have that document show to the end user when they are browsing the product detail section, through means of a link and download.
So I figured I would chop this project up and first attempt to develop the upload function from the admin area.
In case anyone else can help but doesn't know nopCommerce, it is an ASP.NET MVC 3 project. For those who have nopCommerce already, please look below on how to navigate and add my code to the specific files.
1.How to add a tab to Product Edit:
a.Inside Nop.Admin
i.Navigate to Views -> _CreateOrUpdate.cshtml
b.Add TabPanel after line 24
x.Add().Text(T("Admin.Catalog.Products.ProductDocuments").Text).Content(TabProductDocuments().ToHtmlString());
c.Create ‘TabProductDocuments’ help method on line 772
#helper TabProductDocuments()
{
if (Model.Id > 0)
{
<h2>Product Documents</h2>
<form action="" method="post" enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<input type="submit" />
</form>
}
else
{
#T("Admin.Catalog.Products.ProductDocuments.SaveBeforeEdit")
}
}
d.Change ProductDocumentsController.cs to more simple code:
public class ProductDocumentsController : BaseNopController
{
[HttpPost]
public ActionResult Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Server.MapPath("../Content/files/uploads"), fileName);
file.SaveAs(path);
}
return RedirectToAction("Index");
}
Now, the issue I am experiencing is: I can see the tab now in Product Edit, but I cannot upload the file. It submits the query but just refreshes the page and leads back to Product List. No file is uploaded. If you can, please assist me with trying to upload the file properly to the path I have designated. Thank you again for your assistance.
I've already tried from scratch an upload project and it does work properly, but for some reason, here, it just isn't working.
You probably need an Action url in the form's action parameter.
<form action="/Admin/Product/Upload/555" method="post" enctype="multipart/form-data">
And rename your Action method to match
[HttpPost]
public ActionResult Upload(int productId, HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(HttpContext.Server.MapPath("../Content/files/uploads"), fileName);
file.SaveAs(path);
//attach the file to the product record in the database
}
return RedirectToAction("Index");
}
Probably a bit late but I did a plugin for this. Can be found on github
https://github.com/johanlasses/nopcommerce-product-files-plugin

How to do multipart/form-data post in Jetty HttpClient

I'm wondering if someone could help me out there.
For Java project I want to use the Jetty HttpClient that will send data to a Restful webservice.
Have a few questions:
Does Jetty client support multipart/form-data post?
From Jetty doc, to send any data you need to specify the request content by using HttpExchange.setRequestContent(Buffer) Or HttpExchangge.setRequestContentSource(InputStream) method. If I go with setRequestContentSource for file uploading how could I set an additional form params like filename for multipart post?
Is there any way to check a progress of upload using Jetty client? I need a standard thing like a progress bar that shows bytes send, %, etc
Jetty provides a plenty of callbacks like onResponseContent, onResponseStatus, onRequestCommitted, but no one of them could help in monitoring how many bytes have been sent. Is it possible to get an upload progress with Jetty httpclient?
Thank you in advance
You must use MultiPartContentProvider
From: http://download.eclipse.org/jetty/9.3.9.v20160517/apidocs/org/eclipse/jetty/client/util/MultiPartContentProvider.html
A ContentProvider for form uploads with the "multipart/form-data" content type.
Example usage:
MultiPartContentProvider multiPart = new MultiPartContentProvider();
multiPart.addFieldPart("field", new StringContentProvider("foo"), null);
multiPart.addFilePart("icon", "img.png", new PathContentProvider(Paths.get("/tmp/img.png")), null);
multiPart.close();
ContentResponse response = client.newRequest("localhost", connector.getLocalPort())
.method(HttpMethod.POST)
.content(multiPart)
.send();
The above example would be the equivalent of submitting this form:
<form method="POST" enctype="multipart/form-data" accept-charset="UTF-8">
<input type="text" name="field" value="foo" />
<input type="file" name="icon" />
</form>
Use Apache Http client 4.x would help you a bit.
Please see:
http://hc.apache.org/httpcomponents-client-ga/examples.html

form file post to web service method not working

I am trying to have a HTML form post a file to a Asp .Net Web service method. Everything seems to work but there is no form or files on the request object in the web method. any ideas?
Html Form
<form id="formPost" action="service/Post" enctype="multipart/form-data" method="post">
Post File <input id="uploadfile" type=file />
<input type=submit value="Post" />
</form>
Web service
[WebMethod]
public void Post()
{
// file collection of uploaded files in the http context
HttpFileCollection Files = this.Context.Request.Files;
// always 0 and no form either
if (Files.Count > 0)
{}
}
You cannot post to a SOAP web service method using html form. When you submit the form data is encoded using multipart/form-data while a web service expects a SOAP envelope and text/xml content type. In order to invoke the web service you will need to generate a proxy class from the WSDL and use this proxy class to call the desired method.