How to use XQuery and HTML to upload files to MarkLogic? - html

As my question states I am trying to use XQuery and a simple HTML form to upload files to my MarkLogic local database. I already connected to a HTTP-server.
My code now looks like this:
Form:
<div id="content">
<form name="test" action="upload.xqy?uid={xdmp:random()}" method="post"
enctype="multipart/form-data">
<p><label>File to upload:
<input type="file" class="name" name="upload" size="50"/></label></p>
<p><input type="submit" value="Upload and Get Results"/></p>
</form>
</div>
upload.xqy:
let $filename := xdmp:get-request-field-filename("upload")
let $collection := "semansysdocs"
let $fileLocation := xdmp:get-request-path()
return
xdmp:document-load($fileLocation,
map:map() => map:with("uri", $filename)
=> map:with("permissions", xdmp:default-permissions())
=> map:with("collections", $collection)
)
The docs simply state to use xdmp:document-insert(), but I do not understand where.
Is there a way to specify where the file is coming from to get the $fileLocation, or do i need an other method to do this?
Thank you!

Your form is already sending both filename and file data. xdmp:get-request-field-filename('upload') returns the original file path as sent by the browser, and xdmp:get-request-field('upload') will get you the data. I think you are looking for something like:
let $filename := xdmp:get-request-field-filename("upload")
let $file := xdmp:get-request-field("upload")
let $collection := "semansysdocs"
return
xdmp:document-insert(
$filename,
$file,
xdmp:default-permissions(),
(xdmp:default-collections(), $collection)
)
HTH!

Related

Path file issue when uploading csv file via laravel form to database

I want to upload a csv file to my database via a laravel form. I can only insert file if the file is stored into public folder. How can I correctly set path with fopen function?
When submitting form, my code uses only the csv that already exists in public folder and not the csv I try to upload. Except from the csv I also pass some other data to my controller. How can I alter code to receive form file and not public folder stored file?
1) Below is my form excerpt. At the bottom lines I try to upload the file.
<body>
<form method='post' enctype="multipart/form-data" action="/hard">
{{csrf_field()}}
<section>
<br>
<legend><i><b> Complete Data Below</b></i></legend>
<br>
</section>
<section>
Choose program:
<select name="sc" id="xaos">
<optgroup label="postgraduates">
#foreach($transport as $y)
<option value="{{$y->object_id}}">{{$y->object_name}}</option>
#endforeach
</optgroup>
</select>
</section>
<br>
<section>
ID number:
<input name='am' type='number' min="1000000" max="1999999" required="" oninvalid="this.setCustomValidity('1000000 < Value < 1999999')">
</section>
<br>
<section>
Select Language:
<select name="language" id="lang">
<option value="GR"> Greek</option>
<option value="EN"> English</option>
</select>
</section>
<br>
<section>
<label for="upload-file">select csv file</label>
<input type="file" name="upload-file">
</div>
<input type='submit' name='upload' value="Submit!">
</section>
</form>
<br>
<br>
</body>
2) And below is my controller code excerpt which handles file imported.
public function job(Request $p)
{
$a1 = $p -> get('sc');
$a2 = $p -> get('am');
$a3 = $p -> get('language');
$f_rownum = 0;
if (($handle = fopen ( 'MOCK_DATA.csv', 'r' )) !== FALSE)
{
while ( ($data = fgetcsv ( $handle, 1000, ';' )) !== FALSE )
{
$ac1=$data[0];
$ac2=iconv("Windows-1253", "UTF-8", $data[1]);
$ac3=iconv("Windows-1253", "UTF-8", $data[2]);
$ac4=iconv("Windows-1253", "UTF-8", $data[3]);
$ac5=$data[4];
...............
According to Laravel documentation you can store your csv file into the storage like this:
public function storeFile(Request $request)
{
$path = $request->file('upload-file')->store('{directoryName}');
return $path;
}
The above code store your file in storage and returns tha path which you can save it into your DB.
For retrieving the file, you can use this code if you want to force user to download the file:
return Storage::download('{pathWhichYouSavedInDB}');
or you can retrieve the content of the file by using this code:
$contents = Storage::get('{pathWhichYouSavedInDB}');
[I add the extra response which I wrote in the comments]
fopen requires a full-path url of the stored file to be able to open it. So you can get the file url and then pass it to the fopen function like this:
$url = Storage::url('file.jpg');
Or you can not to use fopen at all and just use the $contents which you already retrieved with
$contents = Storage::get('{pathWhichYouSavedInDB}');

MeteorJS: How to get id to load from collection

I'm trying to load an array (with simple text) and trying to load it up on the template whenever it is called. How do I get the ID from that specific item to get the array that I stored in it?
HTML Template:
<template name="commentMarker">
<div id="viewMarker">
<h3 id="markerTitle">{{markerName}}</h3>
<h6 id="markerCategory">{{markerCategory}}</h6>
<br>
<fieldset>
<legend>Description</legend>
<p>{{markerDescription}}</p>
</fieldset>
<form id="commentForm">
<fieldset>
<legend>Comments</legend>
<input type="text" id="markerId" name="idForComment" value={{markerId}}>
<textarea rows="3" cols="19" name="comment" id="commentArea" placeholder="Insert your comment here..."></textarea>
{{#each comments}}
<p id="oneComment">{{this}}</p>
{{/each}}
</fieldset>
<input type="submit" value="Comment" class="commentButton">
<input type="submit" value="Close" class="exitButton">
</form>
</div>
</template>
JS:
Template.commentMarker.helpers({
comments(){
alert(template.find("#markerId").value);
if(commentArray.length===0) return;
else return commentArray;
}});
This is where I insert the comment into the collection's item and it's working fine
Template.commentMarker.events({
'click .commentButton': function(e, template){
e.preventDefault();
var id = template.find("#markerId").value;
var comment = template.find("#commentArea").value;
Points.update(id, { $push: { comments: comment }});
commentArray = Points.findOne(id).comments;
template.find("#commentArea").value = ' ';
}
I tried with commentArray as a global variable which still is. But I'm at loss how I can get the Id from that specific item, I even put it's Id (with hidden display) in the form to actually be able to insert the comment. But it doesn't help me with showing the comments because I cannot seem to get to this field in the Template.helpers ...
Not entirely sure what you are trying to do. It's almost like as if you are displaying the comments right after you updated in to the collection. It looks like you are doing this entirely on local and not a online collection.
However, storing it as a session would work...or reactive var. Might not be the best solution tho. Basically replace commentArray = Points.findOne(id).comments; with:
Session.set('comments', Points.findOne(id).comments)
Then to get it out in helpers:
let commentArray = Session.get('comments')
It's not safe to use it all the time tho for sensitive data. Also try catch the findOne(id).comments because it does produce errors if it happen to not find it.
NOTE: If you are going to use Meteor.Methods, you cannot use Session. You have to return the id and find it in your helpers.

Upload and retrieve image in Laravel

I need to save the image for an avatar.
Can anyone give me a simple code to save and retrieve image?
I need to:
Save image in folder
Save image name in DB
Finally retrieve on image tag; I have to do it by Query Builder
Form:
<form action="" method="post" role="form" multiple>
{{csrf_field()}}
<legend>Form Title</legend>
<div class="form-group">
<label for="">Your Image</label>
<input type="file" name="avatar">
</div>
<button type="submit" class="btn btn-primary">save</button>
back
</form>
<img name="youravatar" src="">
</div>
Route:
Route::get('pic','avatarController#picshow');
Route::post('pic','avatarController#pic');
Controller:
I have the avatarController, but it is empty because I don't know what to do.
Database:
Table name: avatar
Fields: name id, imgsrc, created_at, Updated_at
Other:
I found this code but I can't find out anything:
if ($request->hasFile('avatar')) {
$file = array('avatar' => Input::file('avatar'));
$destinationPath = '/'; // upload path
$extension = Input::file('avatar')->getClientOriginalExtension();
$fileName = rand(11111,99999).'.'.$extension; // renaming image
Input::file('avatar')->move($destinationPath, $fileName);
}
First, make sure you have the encrypt attribute in your form
<form action="#" method="post" enctype="multipart/form-data">
You can use something similar to this in your controller
public function save(Request $request)
{
$file = $request->file('file');
// rename your file
$name = $file->getClientOriginalName();
\Storage::disk('local')->put($name, \File::get($file));
return "file saved";
}
Yes, you should store the file route in your database as well.
Make sure you are using a consistent path for your images like
Finally you have to create a route to give public access to your image file, like so:
Route::get('images/{file}', function ($file) {
$public_path = public_path();
$url = $public_path . '/storage/' . $file;
// file exists ?
if (Storage::exists($archivo))
{
return response()->file($pathToFile);
}
//not found ?
abort(404);
});
Check the docs about Laravel Responses
I hope this gives you an Idea of what to do.
Upload Image in laravel 5.4
check if request has image
$request->hasFile('image')
OR
$request->file('image')->isValid()
Now Save Image
$request->inputname->store('folder-name') return image path 'folder name/created image name
$request->image->store('images')
Check if image exits
Storage::disk('local')->exists('image name');
Delete Image
Storage::delete('image');
This is my code
if ($request->hasFile('image') && $request->file('image')->isValid())
{
$path = $request->image->store('images');
if(!empty($path)){
$edit = Model::FindOrFail($id);
// Delete old image
$exists = Storage::disk('local')->exists($edit->image);
if($exists){
Storage::delete($edit->image);
}
$edit->image = $path;
$edit->save();
}
}
Reference

Uploading images to database in codeigniter?

I tried searching but no success i want to upload max 5 images to database along with user form data.I have table where all user data of form posted is saved along with images uploaded[image upload is attached with user form] picture fields in database are named as pic1,pic2,pic3.. pic5 + email,password etc I am successfull in uploading image data to database but not images.
//controller
if ($this->form_validation->run()!=true) {
$data['countryDrop'] = $this->Country_states_cities->getCountries();
$this->load->view('header');
$this->load->view('register',$data); //Display page
$this->load->view('footer');
}else{
$form=array();
$form['first_name']=$this->input->post("first_name",true);
$form['last_name']=$this->input->post("last_name",true);
$form['dob']=date('Y-m-d',strtotime($this->input->post("dob",true)));
$form['email']=$this->input->post("email",true);
$form['password']=sha1($this->input->post("password",true));
$form['phone']=$this->input->post("phone",true);
$form['addline2']=$this->input->post("addressline2",true);
$form['zip']=$this->input->post("zip",true);
$result = $this->Couch_reg->insert_new_user($form); //call to model
//model
function insert_new_user($form)
{
$this->db->insert('tbl_usrs',$form);
if ($this->db->affected_rows() > 0) {
return true;
} else {
return false;
}
}
//view
<input type="file" name="uploadfile[]" accept = "image/*" multiple = "multiple" size="20" /> <br />
as we can see model part is very short i want to collect images name in array form and send it to database.
You need to save the images in the upload folder and save the image name in the database.
<html>
<body>
<form method="POST" action="<?php echo site_url('my-controller/file_upload');?>" 'enctype'=>'multipart/form-data'>
<label for="file">Filename:</label>
<input type="file" name="userfile[]" id="file" multiple>
<input type="submit" value="upload"></form>
</body>
</html>
Then create controller
make funtion inside it:
$files = $_FILES;
$cpt = count($_FILES['userfile']['name']);
for($i=0; $i<$cpt; $i++)
{
$_FILES['userfile']['name']= $files['userfile']['name'][$i];
$_FILES['userfile']['type']= $files['userfile']['type'][$i];
$_FILES['userfile']['tmp_name']= $files['userfile']['tmp_name'][$i];
$_FILES['userfile']['error']= $files['userfile']['error'][$i];
$_FILES['userfile']['size']= $files['userfile']['size'][$i];
$this->upload->initialize($this->set_upload_options());
$this->upload->do_upload();
$fileName = $_FILES['userfile']['name'];
$images[] = $fileName;
Hope this will help you.
For more you can try this: http://w3code.in/2015/09/upload-file-using-codeigniter/

How to process a POST request in SWI-Prolog?

I have an HTML form like this one:
<form action="test" method="post">
<input name="first_name" type="text"/>
<input name="last_name" type="text" />
<input name="age" type="text" />
<input type="submit" value="Send"/>
</form>
How do I get the values of the input fields and print them on screen, just like in any other procedural programming language such as PHP, ASP or JSP?
I tried to solve the problem the following way:
:- use_module(library(http/thread_httpd)).
:- use_module(library(http/http_dispatch)).
:- http_handler(root(test), reply, []).
:- http_handler('test', reply, []).
server(Port) :-
http_server(http_dispatch, [port(Port)]).
reply(Request) :-
member(method(post), Request), !,
http_read_data(Request, Data, []),
format('application/x-www-form-urlencoded', []),
format(Data).
That brought me nothing more than an error with the 500 code (internal server error).
You should use the http/http_client library (:- use_module(library(http/http_client))).
Additionally, I'm not sure how having two handlers for test will work.
Finally, I think that format(Data) might not work, especially since it is expected to return an html document.
By the way, to retrieve the values of the fields you can do something like:
http_read_data(Request, [first_name=FN, last_name=LN, age=A|_], []).
I'm pretty new with the http prolog lib, I would suggest checking http://www.pathwayslms.com/swipltuts/html/
Essentially, you'll handle the request like normal, checking that the method(Method) term in the request is method(post).
http_read_data will read the request body.
the body will be encoded like an URI query string, so uri_query_components/2
will convert it to a list of Key=Value terms
?- uri_query_components('a=b&c=d%2Bw&n=VU%20Amsterdam', Q).
Q = [a=b, c='d+w', n='VU Amsterdam'].
For others looking for similar info - if your response is json, you can use read_json_dict to get the data as a dict.
I use library(http/http_parameters). With that, I can do
load_graph(Request) :-
http_parameters(Request,
[path(Path, [atom]),
aperture(Aperture, [integer])]),
where load_graph is the handler for the form
...
html(form([action(Ref)],
dl([dt('Root Path'), dd(input([name=path, type=text, value=Default])),
dt('Aperture'), dd(select([name=aperture], Aplist)),
dt('Go!'), dd(input([type=submit, value='Load!']))
]))).