OrientDB - upload image via HTTP API - javascript

Hey OrientDB Community.
I'm attempting to upload an image into my DB via HTTP API. In my super basic web-page, I select a file and click upload. Simple. Once the button is clicked, I have javascript handling it with jquery and ajax.
Context: This is an educational tool which will have student profiles with their pictures. These images won't be too big (10MB - 20MB-ish).
Here is the HTML upload form:
<h2 class="heading-blue">Upload Image</h2>
<form enctype="multipart/form-data">
<input name="file" type="file" />
<input id="upload_image" type="button" value="Upload" />
</form>
Here is the javascript code:
$('#upload_image').on('click',function(){
console.log("UPLOADING IMAGE");
var formData = new FormData($('form')[0]);
$.ajax
({
type: "POST",
url: "http://localhost:2480/uploadSingleFile/DemoPlayground",
data: formData,
??
??
success: function (){
alert('SUCCESS!');
}
});
});
I'm not sure what to use where it says "/uploadSingleFile/" in the ajax URL parameter. Also, I'm not sure what else needs to be included in the ajax call. (Hence the "??"'s up above).
Some possibilities that I've been reading about:
Call a server-side function and pass the binary data (the image) to the function for it to handle the rest. If this is a good idea, I'm not sure how to do it...so help would be appreciated.
I've read in a couple places that Orient uses Jetty to perform this action. Any pointers on that?
I've got other types of HTTP API to OrientDB requests working, but this one is troublesome and I can't figure it out on my own.
I'm open to looking at this from new angles. Please help! :) THANKS!

Related

Flask uploading files to flask without form

I want to be able to upload my file from javascript without using the typical HTML form so that the page doesn't have to refresh when uploading the file to python.
I have not had any success getting my file with request.files.
I have tried two different versions, one using an HTML form and one without.
When trying out the one with the HTML form, the output from request.files is an ImmutableMultiDict that looks like this ImmutableMultiDict([('file', <FileStorage: '^RUT.csv' ('text/csv')>)]) whilst according to my understanding, it is supposed to be a dictionary.
Here is the code:
<form method="POST" action="/get_dims" enctype="multipart/form-data" id="import_form">
<input type="file" name="file" accept=".csv" id="training_set_import" value="import training set"/>
<input type="submit" value="Submit">
</form>
#app.route("/get_dims", methods=["POST"])
def getDatasetDims():
file_n = request.files
print("Got it!")
print(file_n)
return "None"
The other, preferable method I have tried is with javascript using AJAX. When doing this, request.files returns an empty ImmutableMultiDict that looks like this ImmutableMultiDict([]). Here is my code for this:
$(function(){
$("#training_set_import").change(function(){
var file_name = $("#training_set_import").val();
var form = $("#training_set_import").form;
var data = new FormData(form);
if (file_name !== ""){
$.ajax({
type: "POST",
url:"/get_dims",
enctype: "multipart/form-data",
data: {"file": data},
cache: false,
processData: false,
contentType: false
});
}
});
});
The python code is the same.
So my question is, how can I implement the javascript version of this so that I can manupulate the uploaded csv in python ?
Okay i found a thread on here that solved my issues. Here it is: How to upload a file using an ajax call in flask
Hope this helps anyone with the same issue as me !

Javascript Ajax upload file to Python backend

I got stuck how to make my code work, I am trying to upload file using javascript to my python code.
here my HTML
<div class="form-group">
<label for="upload_list" class="control-label">Upload List</label>
<input name="upload_list" id="upload_list" type="file" class="form-control" multiple="true" />
</div>
<a id="make_order" role="button" class="btn btn-primary" href="#">
here my JS that handle the upload.
$("a#make_rfq_order").bind("click", function(ev) {
var customer_upload_list = $('#upload_list').val();
ajax.jsonRpc('/shop/order', 'call', {
'upload_list': customer_upload_list
});
});
and here my python code
def customer_order(self, **post):
if post.get('upload_list'):
.....
if order and order.id:
.....
if post.get('upload_list'):
.....
values.update({
'name': '{0}_{1}'.format('file', upload_list.filename),
})
order.write(values)
return True
if I use 'name': '{0}_{1}'.format('file', upload_list), its work, but only handle the file name,
how to get the actual file submited to my server?...
I'm unable to comment, so I'm answering as best I can, but knowing a bit more about your python server would help (are you using a specific framework or did you code your own python server from scratch, etc...)
I think you're sending the path of the file, not the file itself with this part:
var customer_upload_list = $('#upload_list').val();
Try the below instead:
var file = $('#upload_list').get(0).files[0];
Also, it looks like you're trying to include support for multiple files.
Have you tried building a FormData by iterating over the selected files and adding the FormData to the POST?
Something like this may work, or at least get you in the right direction:
var files = new FormData();
for(var i=0;i< $('#upload_list').val().length;i++){
var file = $('#upload_list').get(0).files[i];
files.append('files[]', file);
}
$.ajax({
url: 'upload.php',
type: 'POST',
data: files
});
the received data will be in list form on the server side, so remember to alter the code to look for a list.
You may have to play around with other paramaters in the POST, like contentType and dataType or processData, but I think the above is sufficient to get a result

upload file via ajax with jquery easy ui

I'm trying to give users the possibility to import data from a file that is located on their computer by using jQuery EasyUI form widget:
<form id="my_form" method="POST">
<input type="file" name="my_file" id="my_file" />
</form>
var file_name = $('#my_file').val();
if(file_name)
{
$('#my_form').form('submit', {
url: [url_to_call],
onSubmit: function(param){
param.file_path = file_name;
}
});
}
Then when the user browse on his/her computer for the file, I wanna send the path to a jQuery ajax query to perform some upload action. The problem I have is that filename returns something like this:
C:\fakepath\[name_of_file]
Because of the fakepath string, I am not getting the real path to where the file is located on the user's computer. Does anybody know how I can fix this issue please?
Thank you
Tried this plugin http://malsup.com/jquery/form/#getting-started
this plugin provide a method called AjaxSubmit() which work fine for upload the image. I have used it in 2011.
it's have some issue in IE (old version like 6,7). You need to write some hacks. on the backend Firefox and IE upload the correct file-stream format like Data/Image but in Chrome (Webkit) you will got Octet Stream. You need to parse the file format on server to check that file is not wrong.
I have no idea what your form() function does, as no such method exists in jQuery, but the usual way of uploading a file to the server would be something like this :
$('#my_file').on('change', function() {
$.ajax({
url : [url_to_call],
data : new FormData($('#my_form').get(0)),
processData: false,
contenttype: false
}).done(function(param) {
param.file_path = file_name;
});
});

Get data using POST and AJAX

I'm trying to send some data in my server asynchronously using AJAX.
I need to send the data using the POST method because the data sent are quite
many characters and by using GET the created URL will be too big. Well that's not a problem, but for aesthetically reasons I would rather have small URLs. In order to do so I used the solution (question) explained here.
My Javascript code sending the data is:
var code = "code=" + document.getElementById("code_area").value;
xmlhttp.open("POST", "run_code.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(code);
The above code is executed when I click a button, but then the URL changes to this: localhost/code.php?code=datadatadatadatadatadatadatadatadatadatadatadatadatadata which seems is no different of using GET instead (my URL has become quite big). I used POST, not GET but still data seems to get transmitted by the URL. Any ideas why is this happening?
You could do that much more easily using jQuery.
$.post("run_code.php", { code: $("#code_area").val() });
Links:
How to add jQuery support to your code.
jQuery documentation.
$.post() documentation.
Way easier with jquery...
$.post( 'yoururlhere.com/phppage',
{code:$("#code_area").val()},
function(responseData){
// responseData is the echo'd data set from your php page
}, 'json'
);
the data within { } are the post K-V pairs
responseData is the dataset echo'd back from php
The problem after all was that I was using a submit input field in my HTML page like this:
<input type="submit" />
which when used changed (refreshed) the URL.
By using:
<input type="button" />
the problem has been fixed.

Ajax using file upload

I am creating mail page for sending mails. I need to attach some file before sending. How could I do this using AJAX? Initially I need to store those files in server and then I have to send the mail. These actions are done with in a single send button.
Check these questions:
JavaScript file uploads
How can I get Gmail-like file uploads for my web app?
What is the best multiple file JavaScript / Flash file uploader?
Look on below snippet which send text data and attached multi-files. The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server).
async function sendEmail() {
let formData = new FormData();
let msg = { message: emailText.value };
formData.append("email", JSON.stringify(msg));
[...attachment.files].map( (file,i) => formData.append("file"+i, file) );
try {
await fetch('your/api/upload/email', { method: "POST", body: formData });
alert("Email was send!");
} catch(e) {
alert("Problem with email sending");
}
}
<textarea id="emailText" placeholder="Type message here"></textarea><br>
<input type="file" id="attachment" multiple /><br><br>
<input type="button" value="Send email" onclick="sendEmail()" />
<br><br><span style="color:red">In this snippet API not exists so exception will be thrown but you can look on your request in:<br> chrome console> network tab</span>
I hope you know how do the normal upload. Call the upload/Reading and updating the file when click the button by using the ajax call. You have to send the local system file path as the input and then the response should contain the path in the server or error. Update the attachment link with the response in case there are no errors.
You should dynamically create a hidden iframe in your DOM and set the target of your upload form to this iframe. dont forget to set form method to POST.
you could do both uploading and message field filling in one go.
you should definitely check ready components doing this for the javascript library of your choice.

Categories

Resources