I am trying to upload images directly from the browser to the Google Cloud bucket. I am using gcs-signed-urls on the backend and followed this example.
Here is my Form upload which is working fine.
<form action={"https://" +this.state.imageForm.bucket +".storage.googleapis.com"} method="post" enctype="multipart/form-data">
<input type="hidden" name="key" value={this.state.imageForm.key}></input>
<input type="hidden" name="bucket" value={this.state.imageForm.bucket}></input>
<input type="hidden" name="GoogleAccessId" value={this.state.imageForm.GoogleAccessId}></input>
<input type="hidden" name="policy" value={this.state.imageForm.policy}></input>
<input type="hidden" name="signature" value={this.state.imageForm.signature}></input>
<input type="hidden" name="Content-Type" value={this.state.imageForm.contenttype}></input>
<input name="file" type="file"></input>
<input type="submit" value="Upload"></input>
Now I am trying to turn this into form post request using Axios.
let data = new FormData();
data.append("key",this.state.imageForm.key+ "." + picture[0].type.replace("image/", ""))
data.append("bucket", this.state.imageForm.bucket);
data.append("GoogleAccessId", this.state.imageForm.GoogleAccessId);
data.append("policy", this.state.imageForm.policy);
data.append("Content-Type", 'application/octet-stream');
data.append("file", picture[0]);
console.log("data", data);
let config = {
headers: {
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
}
}
let result = await axios.post("https://" + this.state.imageForm.bucket + ".storage.googleapis.com",
data, config)
I am getting 2 errors:
1 - CROS error
create:1 Access to XMLHttpRequest at 'https://ccc.storage.googleapis.com/' from origin 'http://127.0.0.1:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
2- Post request is failing with 400 error with the response.
Here is a snapshot from the developer console.
I also updated the Cors file for my bucket, here is the config
{
"origin": [*],
"responseHeader": ["Content-Type", "access-control-allow-origin"],
"method": ["GET", "HEAD", "DELETE", "PUT", "POST"],
"maxAgeSeconds": 3600
}
I found the following note in the API POST method docs
Note: The POST object method does not support signed URLs, except in the case of resumable uploads.
So you can try the PUT method or doing a resumable upload as stated at the docs
Related
I am trying to add a Paypal Payments button onto our website. I have Auto Return and Payment Data Transfer turned on.
When I point to sandbox, everything works correctly and it returns to my website with the transaction id in the url.
When I point to production PayPal, no transaction id is returned. Payment does go through.
Here is the form code:
<form action="#VARIABLES.strHostAddress#" method="post" target="_top" id="testform">
<input type="hidden" name="cmd" value="_donations">
<input type="hidden" name="business" value="#VARIABLES.strBusinessEmail#">
<input type="hidden" name="item_name" value="#VARIABLES.strGiftDesignation# - #VARIABLES.strGiftDesignation2#">
<input type="hidden" name="amount" value="#VARIABLES.intPayAmt#">
<input type="hidden" name="first_name" value="#VARIABLES.strFirstName#">
<input type="hidden" name="last_name" value="#VARIABLES.strLastName#">
<input type="hidden" name="address1" value="#VARIABLES.strLine1#">
<input type="hidden" name="address2" value="#VARIABLES.strLine2#">
<input type="hidden" name="city" value="#VARIABLES.strCity#">
<input type="hidden" name="state" value="#VARIABLES.strState#">
<input type="hidden" name="zip" value="#VARIABLES.strPostalCode#">
<input type="hidden" name="email" value="#VARIABLES.strEmail#">
<input type="hidden" name="cancel_return" value="#VARIABLES.strCancelPage#">
<input type="hidden" name="return" value="#VARIABLES.strThankYouPage#">
<input type="hidden" name="rm" value="2">
</form>
where #VARIABLES.strHostAddress# is "https://www.paypal.com/cgi-bin/webscr" for live or "https://www.sandbox.paypal.com/cgi-bin/webscr" for sandbox.
Any suggestions or idea why this would happen?
I am including a step by step explanation that PayPal has on their developers website and the important part is that you get the "tx" value, and send it back with the PDT "Identity Token" which you can find on the PayPal account when you login to configure PDT.
The following steps illustrate the basic flow of a PDT transaction.
"A customer submits a payment.
PayPal sends the transaction ID of the payment through HTTP as a GET variable (tx). This information is sent to the Return URL you specified in your PayPal account profile.
Your return URL web page contains an HTML POST form that retrieves the transaction ID and sends the transaction ID and your unique PDT token to PayPal.
PayPal replies with a message indicating SUCCESS or FAIL. The SUCCESS message includes transaction details, one per line, in the = format. This key-value pair string is URL encoded."
Ok, I just found this GitHub link that gives various code versions of how to get the "tx" and use it and the Identity Key to get all the name value pairs and parse them. It has an example in each language. Just click on the file name.
// ASP .NET C#
using System;
using System.IO;
using System.Text;
using System.Net;
using System.Web;
using System.Collections.Generic;
public partial class csPDTSample : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// CUSTOMIZE THIS: This is the seller's Payment Data Transfer authorization token.
// Replace this with the PDT token in "Website Payment Preferences" under your account.
string authToken = "Dc7P6f0ZadXW-U1X8oxf8_vUK09EHBMD7_53IiTT-CfTpfzkN0nipFKUPYy";
string txToken = Request.QueryString["tx"];
string query = "cmd=_notify-synch&tx=" + txToken + "&at=" + authToken;
//Post back to either sandbox or live
string strSandbox = "https://www.sandbox.paypal.com/cgi-bin/webscr";
string strLive = "https://www.paypal.com/cgi-bin/webscr";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(strSandbox);
//Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
//Send the request to PayPal and get the response
StreamWriter streamOut = new StreamWriter(req.GetRequestStream(), System.Text.Encoding.ASCII);
streamOut.Write(query);
streamOut.Close();
StreamReader streamIn = new StreamReader(req.GetResponse().GetResponseStream());
string strResponse = streamIn.ReadToEnd();
streamIn.Close();
Dictionary<string,string> results = new Dictionary<string,string>();
if(strResponse != "")
{
StringReader reader = new StringReader(strResponse);
string line=reader.ReadLine();
if(line == "SUCCESS")
{
while ((line = reader.ReadLine()) != null)
{
results.Add(line.Split('=')[0], line.Split('=')[1]);
}
Response.Write("<p><h3>Your order has been received.</h3></p>");
Response.Write("<b>Details</b><br>");
Response.Write("<li>Name: " + results["first_name"] + " " + results["last_name"] + "</li>");
Response.Write("<li>Item: " + results["item_name"] + "</li>");
Response.Write("<li>Amount: " + results["payment_gross"] + "</li>");
Response.Write("<hr>");
}
else if(line == "FAIL")
{
// Log for manual investigation
Response.Write("Unable to retrive transaction detail");
}
}
else
{
//unknown error
Response.Write("ERROR");
}
}
}
PDT-Code-Samples on GitHub
Actually, I need to implement the PayUMoney with Ionic 3. I know, I don't have proper plugin. But I need to integrate the PayUMoney processing with my Server and send the acknowledgement to ionic 3.Please Guide me to solve this issue.
I'm not sure if you have found the solution already, but this might help others looking for the answer.
So lets assume you have all the required post parameters(You either have it locally somehow or get it from your server).
this.paymentString = `
<html>
<body>
<form action="${this.post_url}" method="post" id="payu_form">
<input type="hidden" name="firstname" value="${this.firstname}"/>
<input type="hidden" name="email" value="${this.email}"/>
<input type="hidden" name="phone" value="${this.phone}"/>
<input type="hidden" name="surl" value="${this.surl}"/>
<input type="hidden" name="curl" value="${this.curl}"/>
<input type="hidden" name="furl" value="${this.furl}"/>
<input type="hidden" name="key" value="${this.key}"/>
<input type="hidden" name="hash" value="${this.hash}"/>
<input type="hidden" name="txnid" value="${this.txnid}"/>
<input type="hidden" name="productinfo" value="${this.productinfo}"/>
<input type="hidden" name="amount" value="${this.amount}"/>
<input type="hidden" name="service_provider" value="${this.service_provider}"/>
<button type="submit" value="submit" #submitBtn></button>
</form>
<script type="text/javascript">document.getElementById("payu_form").submit();</script>
</body>
</html>`;
console.log(this.paymentString);
this.paymentString = 'data:text/html;base64,' + btoa(paymentString);
So basically now you have a base64 html string which you can pass to your InAppBrowser(from ionic native).
Please find how to include InAppBrowser in your project from ionic native docs (PS: Include InAppBrowser in app.modules.ts as well).
constructor(private iab: InAppBrowser) { }
Next step is to open the your base64String inAppBrowser and listen for completion of the transaction.
const browser = this.iab.create(payString, "_self", {
location: 'no',
clearcache: 'yes',
hardwareback: 'no',
});
browser.on('loadstart').subscribe((event: InAppBrowserEvent) => {
if (event.url === this.surl) {
this.paymentSuccess();
} else if (event.url === this.furl) {
this.paymentFailure();
}
});
What you do in functions paymentSuccess and paymentFailure is up to you.
That is it, should work as required.
Read further if you intend to send json data in 'productinfo'
You need to convert it to htmlsafe characters.
So replace this line
<input type="hidden" name="productinfo" value="${this.productinfo}"/>
with
<input type="hidden" name="productinfo" value="${this.htmlEntities(this.productinfo)}"/>
and have a function to convert json data to html safe characters,
private htmlEntities(str) {
return String(str)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"');
}
I am trying to upload a file i can able to upload a file but i need to post one parameter present in the form, now i need to post one parameter and upload file in the form.
I tried Multi part and Form url encoded in the consumes annotation. It is not working i am getting an error.
I used #FormDataParam and #FormParam annotation in the method.
java.lang.NullPointerException
org.glassfish.jersey.media.multipart.internal.FormDataParamValueFactoryProvider$FormDataParamValueFactory.provide(FormDataParamValueFactoryProvider.java:203)
org.glassfish.jersey.server.spi.internal.ParameterValueHelper.getParameterValues(ParameterValueHelper.java:81)
org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.getResource(SubResourceLocatorRouter.java:220)
org.glassfish.jersey.server.internal.routing.SubResourceLocatorRouter.apply(SubResourceLocatorRouter.java:133)
org.glassfish.jersey.server.internal.routing.RoutingStage._apply(RoutingStage.java:128)
Server side:
#POST
#Path("import")
#Consumes(MediaType.MULTIPART_FORM_DATA)
#Produces(MediaType.APPLICATION_JSON + "; charset=UTF-8")
public void uploadScenario(#FormDataParam("importScenario") final InputStream is,
#FormDataParam("complectId") final Long complectId) {
// Realisation
}
Client side:
<form id="importForm" target="my_iframe" action="rest/exportimport/import" method="post" enctype="multipart/form-data">
<input id="uploader" type="file" name="importScenario" size="50"><input type="submit">
<input type="text" style="display:none" name="complectId" value="'+id+'">
</form>
I'm trying to write a client that does all four REST verbs (GET/POST/PUT/DELETE) and have gotten all but the PUT done. The REST/CRUD API I'm working from wants to update an entry by calling PUT /realmen/ID-string and including the key-value pairs as JSON. For a POST this seems to work "automatically", but not for a PUT.
My HTML looks like:
<div id="list">
<form novalidate class="edit-form">
<p>Title <input ng-model="realmen.title" type="text" value="{{realmen.title}}" /></p>
<p>Real Men <input ng-model="realmen.realmen" type="text" value="{{realmen.realmen}}" /> </p>
<p>Real Role-Players <input ng-model="realmen.realroleplayers" type="text" value="realmen.realroleplayers}}" /></p>
<p>Loonies <input ng-model="realmen.loonies" type="text" value="{{realmen.loonies}}" /></p>
<p>Munchkins <input ng-model="realmen.munchkins" type="text" value="{{realmen.munchkins}}" /></p>
<input ng-model="realmen.entryId" type="hidden" value="{{entryId}}"/>
<button ng-click="change()">UPDATE ({{entryId}})"</button></p>
</form>
</div>
My controller looks like:
$scope.realmen = RealMen.get({entryId: $routeParams.entryId}, function() {
$scope.master = angular.copy($scope.realmen); // For resetting the form
});
$scope.change = function() {
console.log($scope.realmen);
RealMen.update({entryId: $scope.entryId}, function() {
$location.path('/');
});
}
And finally, my services look like:
angular.module('realmenServices', ['ngResource']).
factory('RealMen', function($resource){
var RealMen = $resource(
'http://localhost\\:3000/realmen/:entryId',
{},
{
query: {method:'GET', params:{entryId:''}, isArray:true},
post: {method:'POST'},
update: {method: 'PUT', params:{entryId:'#entryId'}},
remove: {method:'DELETE'}
});
return RealMen;
});
The PUT is getting called with the correct id value in the URL, but the Request Payload only contains the entryId, so the backend API gets no expected keys and values and essentially blanks out the record in the database.
The console.log($scope.realmen) does show the form fields, along with a lot of extra data. I tried calling RealMen.update($scope.realmen, ...) (similarly to calling .save()), but all those extra fields are tacked on as query string parameters to the URL in a spectacularly ugly fashion.
Because your $scope.realmen is a resource instance, instead of using RealMen.update, you can just call $scope.realmen.$update() (note that there is a "$"). The instance action method will take care of sending the data for you.
I'm very very new on HTML5 development and this question could be very silly but I've found an answer for it (or I've searched very well).
I want to send a form to a web service via post (I don't want to show all fields in URL).
I have two question:
How must I named forms fields? If I trying to send an userName I think I have to put this test as ID to the field which will held that value.
And this is because I'm so curious. Which is the post message content which is sent to web service?
This is an example that I've found searching Internet:
<FORM action="http://somesite.com/prog/adduser" method="post">
<P>
<LABEL for="firstname">First name: </LABEL>
<INPUT type="text" id="firstname"><BR>
<LABEL for="lastname">Last name: </LABEL>
<INPUT type="text" id="lastname"><BR>
<LABEL for="email">email: </LABEL>
<INPUT type="text" id="email"><BR>
<INPUT type="radio" name="sex" value="Male"> Male<BR>
<INPUT type="radio" name="sex" value="Female"> Female<BR>
<INPUT type="submit" value="Send"> <INPUT type="reset">
</P>
</FORM
I think I will need those ids to get those values while processing them on web service, isn't it?
It depends, you could do a post to a page with a redirect (in .NET you would handle it this way):
<form action="http://myurl/postpage.ashx" method="post">
<input name="forename" />
<input name="surname" />
<input type="submit" value="Submit" />
</form>
And then pick this up in the server side script at postpage.ashx using:
string forename = Request["forename"];
string surname = Request["surname"];
You could also use jQuery to make an ajax call to the same page using the following:
var forename = $("input[name=\"forename\"]").val();
var surname = $("input[name=\"surname\"]").val();
$.ajax({
url: "http://myurl/postpage.ashx",
type: "POST",
async: true, // set to false if you don't mind the page pausing while waiting for response
cache: false,
dataType: "json",
data: "{ 'forename': '" + forename + "', 'surname': '" + surname + "' }",
contentType: "application/json; charset=utf-8",
success: function(data) {
// handle your successful response here
},
error: function(xhr, ajaxOptions, thrownError) {
// handle your fail response here
}
});
You would handle the post in the server side code the same way. The key thing to note here is that whatever you enter as the name attribute of your input element is what will get POSTed as a key/value pair to your receiving URL.
every web service should give you something like WSDL which normally contains specification of available fields and methods you can use. if the webservice you are connecting to have url webservice.com than try webservice.com/wsdl to get the WSDL.
Check this topic: click
Attribute "name" is the one that needs to be unique in order to pass that parameter to a Servlet (or wherever). The post method then encrypts the message and sends it to the Servlet.
<form method="post" action = "LoginServlet">
Name: <input type="text" name="userName">
Password: <input type="password" name="password">
<input type="submit" name = "Login" class="button">
</form>
In order to access that data you will do something like this in the Servlet:
String userName = request.getParameter("userName");