I'm in a quandary on how to get this working.
In Postman, I can upload an attachment without any issue.
I'm uploading a simple text file.
The code from postmanshows this:
var form = new FormData();
form.append("uploadFile", "C:\\temp\\test.txt");
var settings = {
"async": true,
"crossDomain": true,
"url": "https://xxxxxxx.service-now.com/api/now/attachment/file?table_name=problem&table_sys_id=oiui5346jh356kj3h634j6hk&file_name=Toast",
"method": "POST",
"headers": {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx==",
"Cache-Control": "no-cache",
"Postman-Token": "39043b7f-8b2c-1dbc-6a52-10abd25e91c1"
},
"processData": false,
"contentType": false,
"mimeType": "multipart/form-data",
"data": form
}
$.ajax(settings).done(function (response) {
console.log(response);
});
When I use this on an .asp page I get a 400 error and a response from the console that says:
"Failed to create the attachment. File part might be missing in the request."
How do you get the file you want attach into the code correctly. I thought hard coding it in would have worked. How do you get the code to find the file on the local users pc. Once I get this working I eventually want to have a file input button to select the file.
Thanks,
Scott
Your code looks fine except this line:
form.append("uploadFile", "C:\\temp\\test.txt");
Passing the file name as the second parameter won't work, according to the documentation of FormData.append here, you need to pass some blob/file object pointing to the document it self (not a string)
Now there are 2 possible scenarios:
Scenario 1
The user selects the file manually using a browse button
Here you need to add the input to your page and a trigger to upload the file when it's selected, something like below maybe:
uploadDataFile();
function uploadDataFile(fileInput) {
// creates the FormData object
var form = new FormData();
// get the first file in the file list of the input
// (you will need a loop instead if the user will select many files)
form.append("uploadFile", fileInput.files[0]);
// ... the rest of your AJAX code here ...
}
<input type="file" onchange="uploadDataFile(this)" />
Scenario 2
Uploading the file directly without user intervention
Here you need to construct the file object manually same as in this answer and then you will add it normally to your data object
function uploadDataFile() {
// creates the file object
var fileObject = new File (...);
// creates a data object and appends the file object to it
var form = new FormData();
form.append("uploadFile", fileObject);
// ... the rest of your AJAX code here ...
}
One final note
Please pay attention to the browser compatibility for FormData & File objects
Related
I want to use UnityWebRequest to post data into an input field on a website for authorization.
I am able to post data to a website called "https://httpbin.org/post" and I got a success message beeing able to post data to a website:
Success {
"args": {},
"data": "",
"files": {},
"form": {
"data": "LOL"
},
"headers": {
"Accept": "*/*",
"Accept-Encoding": "deflate, gzip",
"Content-Length": "8",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "httpbin.org",
"User-Agent": "UnityPlayer/2021.3.11f1 (UnityWebRequest/1.0, libcurl/7.84.0-DEV)",
"X-Amzn-Trace-Id": "Root=1-63753ab1-7eb673a229988fc954b32ae8",
"X-Unity-Version": "2021.3.11f1"
},
"json": null,
"origin": "31.18.250.181",
"url": "https://httpbin.org/post"
}
but this is just posting data into nothing and I want to post data into an input field like this:
<input type="text" name="_username">
It is for authorization with username and password and later I need to get the text data of a redirect site after logging in.
This is the code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Networking;
using Exception = System.Exception;
public class TestWebRequest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
try
{
string url = "www.ling.com";
WWWForm form = new WWWForm();
form.AddField("_username", "test");
var request = UnityWebRequest.Post(url, form);
//request.SetRequestHeader("Content-Type", "application/json");
//request.SetRequestHeader("Accept", "text/csv");
//request.SetRequestHeader("appKey", "ABC");
StartCoroutine(onResponse(request));
}
catch (Exception e) { Debug.Log("ERROR : " + e.Message); }
}
private IEnumerator onResponse(UnityWebRequest req)
{
yield return req.SendWebRequest();
if (req.isNetworkError)
Debug.Log("Network error has occured: " + req.GetResponseHeader(""));
else
Debug.Log("Success "+req.downloadHandler.text );
byte[] results = req.downloadHandler.data;
Debug.Log("Second Success");
// Some code after success
req.Dispose();
}
}
I can't show the exact link but as I said it has two input fileds one password and one username input field that need to be filled out for authorization and after that I need to submit the form to get redirected were I then want to get the text data from which works with get. I don't know if this is the best way of doing this but I need to access text data on the website that you have to be logged into and it can't be done with cookies (I think) because it are different credentials every time.
Thank you so much for helping!
When you're submitting data, you're actually filling out a form. And then you submit that form. What you need to understand first is that your app does not interact with a website's frontend, it only interacts with the form at hand.
So, say if the website is a PHP website, that would have some logic at some point that gets a user parameter and a password parameter as GET parameters, and would do something based on those.
I cannot recommend this tutorial series enough for what you're trying to do.
Secondly, please do not send passwords over Unity's Web Request utility as plaintext to any website. It is not secure at all. That is a very sensitive subject, you can start off by hashing every password you get as soon as you get it from Unity, and you may submit the hashed form to the database.
And for the last part, the best way of doing this is probably using an API rather than a simple PHP website like the tutorial above.
I am a bit new to Flutter, and I am building a screen that posts data to an API built in PHP mon my hosting server. The API is built by me which receives a JSON object and then saves the data.
The app is working fine, and API is receiving the data, but the http.post seems is firing twice ( calling the API twice)
Which makes my API saves the record twice. there is no possible way for me to check before adding the send record. as My API simply saves a new record so whenever it receives a call it simply saves it and returns back a value for the mobile App ( built in Flutter).
If I use a condition to check, this way the first call will return correct data to the mobile app, but the second one will return an error for the mobile app since the record already exists.
I have read about the Access-Control-Allow-Origin and how it might be the issue and put it my my .httaccess file
<IfModule mod_headers.c>
Header set Access-Control-Allow-Origin "*"
</IfModule>
but no luck.
any idea.
Note I am using a shared hosting.
Code I use in Flutter:
class _PostADToServerState extends State<PostADToServer> {
Future<List<JSBResponse>> _postRequest() async {
// print('Call API function is called');
Map<String, dynamic> myAd = {
"isbn10": widget.title.isbn10,
"isbn13": widget.title.isbn13,
... [Some fields]
"titleCondition": widget.title.titleCondition,
"priceIs": widget.title.priceIs,
"school_name": widget.title.schoolName
};
String json = jsonEncode(myAd);
var url = 'https://www.example.com/xapis/save_new_ad.php';
var body = json;
var data = await http.post(url,
headers: {
"Content-Type": "application/json",
"accept": "application/json",
"Access-Control-Allow-Origin": "*",
},
body: body);
var jsonData = jsonDecode(data.body);
Code in my PHP API starts with the following:
$data = file_get_contents('php://input');
$theTitle = json_decode($data);
Then I use the content I find in the $theTitle object as the following:
$title = $theTitle->title;
I am struggling with the creation of a document set via REST API in SharePoint online. The only solution I found doing this was using the old SharePoint 2010 REST interface in the following way:
$http({
method: "POST",
url: url + "/_vti_bin/listdata.svc/" + listTitle,
data: JSON.stringify(docSetOptions),
headers: {
"Accept": "application/json;odata=verbose",
"content-type": "application/json;odata=verbose",
"X-RequestDigest": $('#__REQUESTDIGEST').val(),
"Slug": _spPageContextInfo.siteServerRelativeUrl + "/" + url + docSetOptions.Path + "/" + docSetOptions.Title + "|" + docSetOptions.ContentTypeId,
}
}).success(function (data, status, headers, config) {
logtoconsole("document set created");
}).error(function (data, status, headers, config) {
logtoconsole("document set error");
});
docSetOptions are those:
var folder = new
{
Title = "foo",
Path = "foo",
ContentTypeId = "0x010050D9126DC6276846BF6D869EF2090EAD",
ContentType = "SP.Data.Shared_x0020_DocumentsItem",
};
The id is the id of my custom content type, derived from document set.
Source: http://www.itidea.nl/index.php/create-a-document-set-using-jsom-and-rest/
This works for me, but a regular folder is created. No document set. Does anybody know if this still works in SharePoint Online?
The only entries I found were regarding SharePoint 2013.
Update: I ran the same script against my SharePoint 2013 on Premise Server and it works perfectly. Document set is created. Microsoft changed this a few months ago. It used to be possible!
Okay, I found a solution.
Since a while it is not possible anymore, to create a document set via REST if the sites content type id is used.
In my case, I had to use the id of the content type in the library.
So I went to my library settings, selected my content type and copied it. The
id differs a little. In my case was 0x0120D5200085474276CB6D314E9BC0E6F067D47DBE. But in your case it will look different.
If I use this id my document set is created successfully!
This took me hours to find out.
i am trying to update a specific document by using rest service control.
I have set up the control (documentJsonService, pathInfo, form name etc)
I know that i have to perform a post (patch) request to the url of the service followed by /unid/ (same way as i ve done to read the document using the same rest).
I have an input field and a button. I want to enter a value to the field, press the button and update a field in the document with the value. How can i do this request?
This is the js function i used in worklight to update a document in Domino:
function updateDoc(docId,newValue) {
var identity = Base64.encode("myDominoUsername:myDominoPassword");
path = "/Databases/Temp/dominoApp.nsf/BestRestTest.xsp/updateService/unid/"+docId;
var input = {
method : 'post',
returnedContentType : 'json',
headers:{
Authorization: "Basic "+"b4lzdD234GG3M6SdW1XI=" //base64 encoding of your //credentials, see above. The function Base64.encode can be found by googling about it in //js. So you replace this string with identity variable.
"X-HTTP-Method-Override":"PATCH",
"Content-Type":"application/json"
},
body: {
contentType: 'application/json; charset=utf-8',
content: JSON.stringify({"theField":newValue})
},
path : path
};
return WL.Server.invokeHttp(input);
}
Now on the Domino side i have added an extension library REST control (alternatively you can do it with Domino Data Service). The properties i ve added are:
pathInfo: whatever you want
service: documentJsonService
computeWithForm:true
defaultItems:true
formName:myformName
This is just client side javascript, so you can do it in a similar way from an XPage.
i have tried to send uploaded file to server by using ajax like this
formData.append('foldername',fname);
formData.append('file', file)
$.ajax({
url: 'imageupload',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success:function(response)
{
alert(response);
alert(response.imagename);
}
});
it is send data to server successfully but i have sent response from server like this
res.writeHead(200,{'Content-Type':'text/html', 'Access-Control-Allow-Orgin':'*'});
res.write(JSON.stringify({"imagename":"1.jpeg","imageid":"xxxxxxxxxxxxxxxxxxx"}));
res.end();
i have written two alert in success function . in first alert i got like this
{"imagename":"1.jpeg","imageid":"xxxxxxxxxxxx"}
i have written second alert for to get imagename but i got undefine
so i could not get specific key value. how to resolve this?
change
res.writeHead(200,{'Content-Type':'text/html', 'Access-Control-Allow-Orgin':'*'});
to
res.writeHead(200,{'Content-Type':'application/json', 'Access-Control-Allow-Orgin':'*'});
jquery don't convert a JSON string to Javascript Object if the content type is 'Content-Type':'text/html'. So, 'Content-Type':'application/json' or 'Content-Type':'text/json' will do the magic. You will get the response as Javascript object in the client. So, you can do
alert(response.imagename);//alerts image name