how to extract data from form-data in rust? - rust

I'm wondering how to I get data from form-data. I started to learn about rust and I'm doing CRUD functions:
----------------------------605243336009903535936235
Content-Disposition: form-data; name="id"
123
----------------------------605243336009903535936235
Content-Disposition: form-data; name="name"
TestName
----------------------------605243336009903535936235
Content-Disposition: form-data; name="body"
TestBody
----------------------------605243336009903535936235--
I pretty much wanna get id, name and body out from form-data and I don't know how to do it manually or if there is crate or something that can help me. Do I have to use string slices?

For such thing I would use a crate: in this case e.g. multipart.
https://docs.rs/multipart/0.18.0/multipart/server/struct.Multipart.html
use multipart::server::Multipart;
use std::io::BufRead;
fn main() {
let body = "----------------------------605243336009903535936235\r
Content-Disposition: form-data; name=\"id\"\r
\r
123\r
----------------------------605243336009903535936235\r
Content-Disposition: form-data; name=\"name\"\r
\r
TestName\r
----------------------------605243336009903535936235\r
Content-Disposition: form-data; name=\"body\"\r
\r
TestBody\r
----------------------------605243336009903535936235--";
let mut mp = Multipart::with_body(
body.as_bytes(),
"--------------------------605243336009903535936235",
);
while let Some(mut field) = mp.read_entry().unwrap() {
let data = field.data.fill_buf().unwrap();
let s = String::from_utf8_lossy(data);
println!("headers: {:?}, data: {}", field.headers, s);
}
}
// out:
//
// headers: FieldHeaders { name: "id", filename: None, content_type: None }, data: 123
// headers: FieldHeaders { name: "name", filename: None, content_type: None }, data: TestName
// headers: FieldHeaders { name: "body", filename: None, content_type: None }, data: TestBody

Related

UTF-8 JSON String parse with Node and make an array of objects

I have this data as a String of JSON Objects in to a file -format UTF-8.
I want to create an array of object out of it and query it, according to the keys it contains.
This is the data:
{
"Number": "C",
"Is": true,
"ImageKey": "06",
"image": "/9j/4AAQSkZJRgABAAEAlgCWAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS4wMQD/"
}{
"Number": "A",
"photoNot": false,
"ImageKey": "61",
"image": "/9j/4AAQSkZJRgABAAEAlgCWAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS4wMQD/"
}{
"Number": "L",
"photoIs": false,
"ImageKey": "99",
"image": "/9j/4AAQSkZJRgABAAEAlgCWAAD//gAfTEVBRCBUZWNobm9sb2dpZXMgSW5jLiBWMS4wMQD/"
}
This is what I have tried:
const stringFile = fs.readFileSync('./test.json', 'utf-8')
const res = JSON.stringify(stringFile);
for (const json in stringFile) {
console.log(JSON.parse(JSON.stringify(json)));
console.log(`Driver number of record is ${jsonData.ImageKey}`);
}
Expected result: value for ImageKey
Error:
Unexpected token in JSON at position 176
at JSON.parse ()
Note! The second curly brace is underlined red in VS, message: EOF. json(0).
How can i fix this with code?
Why don't you just import the JSON as plain old JS object?
const data = require('./test.json');
for (const d of data) {
console.log(d);
console.log(`Driver number of record is ${d.ImageKey}`);
}

Why isn't reqwest returning the content length in this request?

I'm confused why I'm not getting any content back from the following function, which uses reqwest:
fn try_get() {
let wc = reqwest::Client::new();
wc.get("https://httpbin.org/json").send().map(|res| {
println!("{:?}", res);
println!("length {:?}", res.content_length());
});
}
I'm expecting this function to display the response object and then give me the content length. It does the first but not the second:
Response { url: "https://httpbin.org/json", status: 200, headers: {"access-control-allow-credentials": "true", "access-control-allow-origin": "*", "connection": "keep-alive", "content-type": "application/json", "date": "Tue, 26 Feb 2019 00:52:47 GMT", "server": "nginx"} }
length None
This is confusing because if I hit the same endpoint using cURL, it gives me a body as expected:
$ curl -i https://httpbin.org/json
HTTP/1.1 200 OK
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: *
Content-Type: application/json
Date: Tue, 26 Feb 2019 00:54:57 GMT
Server: nginx
Content-Length: 429
Connection: keep-alive
{
"slideshow": {
"author": "Yours Truly",
"date": "date of publication",
"slides": [
{
"title": "Wake up to WonderWidgets!",
"type": "all"
},
{
"items": [
"Why <em>WonderWidgets</em> are great",
"Who <em>buys</em> WonderWidgets"
],
"title": "Overview",
"type": "all"
}
],
"title": "Sample Slide Show"
}
}
What is the problem with my function that it does not provide me with the content length?
The reqwest documentation for content_length() is always a good place to start. It states
Get the content-length of the response, if it is known.
Reasons it may not be known:
The server didn't send a content-length header.
The response is gzipped and automatically decoded (thus changing the actual decoded length).
Looking at your example curl output, it contains Content-Length: 429 so the first case is covered. So now lets try disabling gzip:
let client = reqwest::Client::builder()
.gzip(false)
.build()
.unwrap();
client.get("https://httpbin.org/json").send().map(|res| {
println!("{:?}", res);
println!("length {:?}", res.content_length());
});
which logs
length Some(429)
so the second case is the issue. By default, reqwest appears to be automatically handling gzipped content, whereas curl is not.
The Content-Length HTTP header is entirely optional, so generally relying on its presence would be a mistake. You should read the data from the request using the other reqwest APIs and then calculate the length of the data itself. For instance, you might use .text()
let wc = reqwest::Client::new();
let mut response = wc.get("https://httpbin.org/json").send().unwrap();
let text = response.text().unwrap();
println!("text: {} => {}", text.len(), text);
Similarly, for binary data you can use .copy_to():
let wc = reqwest::Client::new();
let mut response = wc.get("https://httpbin.org/json").send().unwrap();
let mut data = vec![];
response.copy_to(&mut data).unwrap();
println!("data: {}", data.len());

[Vue warn]: Error in render: “TypeError: Cannot read property ‘sex’ of undefined”

I'm doing a v-for on a parent altoke-layers component, and a v-for on its son component altoke-flyers.
send the array a_c that stores the query, from the father to the son,
this works, but I have error alert in console:
please community, help me understand what I'm doing wrong.
this is the console response
vue.js:597 [Vue warn]: Error in render: "TypeError: Cannot read property 'sex' of undefined"
found in
---> <AltokeFlyers>
<AltokeCapas>
<Root>
-------------------------------------------
warn # vue.js:597
vue.js:1743 TypeError: Cannot read property 'sex' of undefined
at Proxy.eval (eval at createFunction (vue.js:10667), <anonymous>:3:234)
at VueComponent.Vue._render (vue.js:4535)
at VueComponent.updateComponent (vue.js:2788)
at Watcher.get (vue.js:3140)
at new Watcher (vue.js:3129)
at mountComponent (vue.js:2795)
at VueComponent.Vue.$mount (vue.js:8527)
at VueComponent.Vue.$mount (vue.js:10926)
at init (vue.js:4131)
at createComponent (vue.js:5595)
this fraction of code in the html where the parent component is tagged (father)
<altoke-capas v-for="(ab, nb) in a_b"
:key="nb++"
:ab="ab"
:a_c="a_c"
v-bind:id="'Slide' + nb"
v-bind:for="'Slide' + nb"
></altoke-capas>
vue.js code
Vue.component('altoke-flyers',{
props: ['ac'],
template: `
<div>
<div class="isquierda">izquierda</div>
<div class="list">
<label class="img" for="Slide6" >
<div v-html="ac.sex" class="lege"></div>
<img v-bind:src="'./files/ski/webcompleta/files/media/img/img/flyers/' + ac.qui + '/124-186.jpg'">
</label>
</div>
<div class="derecha">derecha</div>
</div>
`
})
Vue.component('altoke-capas',{
props: ['ab', 'a_c'],
template: `
<label class="Slide">
<altoke-flyers v-for="(ac, nc) in a_c"
:key="nc++"
:ac="ac"
v-if="ab.a > 0"
v-bind:class="'content ' + ab.b"
></altoke-flyers>
<altoke-flyers
v-if="ab.a > 0"
v-bind:class="'content ' + ab.c"
></altoke-flyers>
</label>
`
})
var app = new Vue({
el:'.altoke',
data: {
mostrar: false,
a_a: [
{ a: "", b: "pel", m: 0, n: false },
{ a: "Inicio", b: "home", m: 1, n: true },
{ a: "Pedidos", b: "comment", m: 1, n: false },
{ a: "Reporte", b: "bullhorn", m: 1, n: false },
{ a: "Generos", b: "list-alt", m: 1, n: false},
{ a: "Nosotros", b: "chalkboard-teacher", m: 1, n: false},
{ a: "", b: "pel", m: 1, n: false },
{ a: "", b: "pel", m: 1, n: false },
],
a_b: [
{ a: "1", b: "pels", c: "sers", m: 0, n: false },
{ a: "0", b: "", c: "", m: 1, n: true },
{ a: "0", b: "", c: "", m: 1, n: false },
{ a: "0", b: "", c: "", m: 1, n: false },
{ a: "0", b: "", c: "", m: 1, n: false},
{ a: "0", b: "", c: "", m: 1, n: false},
],
a_c:[],
},
created: function(){
if (localStorage.getItem('vlist')){
try {
this.a_c = JSON.parse(localStorage.getItem('vlist'));
} catch(e) {
localStorage.removeItem('vlist');
}
} else {
this.get_contacts();
}
},
methods:{
get_contacts: function(){
//const options = { method: 'post', body: 'foo=bar&test=1' }
fetch("./files/icl/master.php")
.then(response=>response.json())
.then(json=>{localStorage.setItem('vlist', JSON.stringify(this.a_c=json.contactos))})
}
},
})
Good day, I've been somewhat busy and worried about this problem, which apparently was not a big deal.
I sent the necessary variables to the child component,
Vue.component('altoke-capas',{
props: ['ab', 'a_c'],
template: `
<label class="Slide">
<altoke-flyers v-for="(ac, nc) in a_c"
:key="nc++"
:ac="ac"
-------->
:sex="ac.sex"
:qui="ac.qui"
-------->
v-if="ab.a > 0"
v-bind:class="'content ' + ab.b"
></altoke-flyers>
<altoke-flyers
v-if="ab.a > 0"
v-bind:class="'content ' + ab.c"
></altoke-flyers>
</label>
`
})
and in this I added the props that would use them.
Vue.component('altoke-flyers',{
props: {
------>
sex: String,
qui: String,
------>
},
template: `
<div>
<div class="isquierda">izquierda</div>
<div class="list">
<label class="img" for="Slide6" >
|
| |
<div v-html="sex" class="lege"></div> |
<img v-bind:src="'./files/ski/webcompleta/files/media/img/img/flyers/' + qui + '/124-186.jpg'">
</label>
</div>
<div class="derecha">derecha</div>
</div>
`
})

Replacing a value for JSON object in Node.js

I tried replacing the value for the key "Information" from the below JSON Object using the code
"itsmdata.incidentParamsJSON.IncidentContainerJson.replace("Information",option);"
but getting error as object is not defined (Attachment)
{
"ServiceName": "IM_LogOrUpdateIncident",
"objCommonParameters": {
"_ProxyDetails": {
"ProxyID": 0,
"ReturnType": "JSON",
"OrgID": 1,
"TokenID": null
},
"incidentParamsJSON": {
"IncidentContainerJson": "{\"SelectedAssets\":null,\"Ticket\":{\"Caller_EmailID\":null,\"Closure_Code_Name\":null,\"Description_Name\":\"Account Unlock\",\"Instance\":null},\"TicketInformation\":{\"Information\":\"account locked out\"},\"CustomFields\":null}"
},
"RequestType": "RemoteCall"
}
}
If you try to update properties of itsmdata you can try this
let str = itsmdata.objCommonParameters.incidentParamsJSON.IncidentContainerJson;
itsmdata.objCommonParameters.incidentParamsJSON.IncidentContainerJson = str.replace(/Information/gi, option);

Docusign Transform Pdf Fields For multiple recipients?

I saw the DocuSign API can automatically transform and assign pdf fields to a single default recipient (Docusign Transform Pdf Fields For single recipient?).
Is it possible to do the assignment for multiple recipients?
I am hoping to leverage the auto transform feature but at the same time assign different pdf fields to different recipients during envelope creation.
Thanks.
The following sample creates an envelope using the REST API using base64 encoded pdfBytes that represents a PDF document that contains a number of adobe form fields: option field, check boxes, signature fields. We use name of the adobe field to map this field to a DocuSign tag created for each recipient.
Note that the key here is to name each PDF form field with a format that it is easily assignable to recipient by using a wildcard.
Please refer to the Document Parameters (under note) for the rules used to match adobe fields to DS fields. We will be transforming all adobe fields and assigning them to two recipients, to do this we will be creating each signer and tags, the way we will be binding each DS tag created by using wildcards on the tabLabel. We will be also setting values for some of the data fields and we will be selecting radio button grouped in a parent and selecting check boxes that we have created as a result of transforming these fields.
HTTP Headers:
Accept: application/json
X-DocuSign-Authentication: {"Username": "your_sender#mail", "Password":"your_password", "IntegratorKey":"your_integration_key"}
Content-Type: multipart/form-data; boundary=e6e95273-cafb-4dbf-86b8-a1c0ed85b5c5
Resource: https://{env}.docusign.net/restapi/{version}/accounts/{accountId}/envelopes
Method: POST
Payload:
--e6e95273-cafb-4dbf-86b8-a1c0ed85b5c5
Content-Type: application/json
Content-Disposition: form-data
{
"status":"sent",
"emailSubject":"Test transforming pdf forms and assigning them to each user",
"compositeTemplates":[
{
"inlineTemplates":[
{
"sequence":1,
"recipients":{
"signers":[
{
"email":"[replace this with a valid email]",
"name":"Signer One",
"recipientId":"1",
"routingOrder":"1",
"tabs":{
"textTabs":[
{
"tabLabel":"PrimarySigner\\*",
"value":"Signer One"
}
],
"checkboxTabs":[
{
"tabLabel":"PrimarySigner\\*",
"selected":true
}
],
"signHereTabs":[
{
"tabLabel":"PrimarySigner\\*"
}
],
"dateSignedTabs":[
{
"tabLabel":"PrimarySigner\\*"
}
],
"radioGroupTabs":[
{
"groupName":"PrimarySigner\\*",
"radios":[
{
"value":"M",
"selected":true
}
]
}
]
}
},
{
"email":"[replace this with a valid email]",
"name":"Signer Two",
"recipientId":"2",
"routingOrder":"2",
"tabs":{
"textTabs":[
{
"tabLabel":"SecondarySigner\\*",
"value":"Secondary One"
}
],
"checkboxTabs":[
{
"tabLabel":"SecondarySigner\\*",
"selected":true
}
],
"signHereTabs":[
{
"tabLabel":"SecondarySigner\\*"
}
],
"dateSignedTabs":[
{
"tabLabel":"SecondarySigner\\*"
}
],
"radioGroupTabs":[
{
"groupName":"SecondarySigner\\*",
"radios":[
{
"value":"F",
"selected":true
}
]
}
]
}
}
]
}
}
],
"document":{
"documentId":1,
"name":"test.pdf",
"transformPdfFields":true
}
}
]
}
--e6e95273-cafb-4dbf-86b8-a1c0ed85b5c5
Content-Type: application/pdf
Content-Disposition: file; filename="test1.pdf"; documentId=1
Content-Transfer-Encoding: base64
[replace this with a base64 encoded]
--e6e95273-cafb-4dbf-86b8-a1c0ed85b5c5--

Resources