Send multiple files from front end to POST method - javascript

Here is my Code sample: https://jsbin.com/qokiyomivu/edit?html,js,output
How can I send multiple files to my POST method and then attach these with email from the Java method?
Currently if I select multiple files only one is being sent and attached to the email written in the Java method. How to attach all I select ?
FYI, I have declared filesToUpload as MultipartFile like private MultipartFile filesToUpload in my Bean.

That’s a good question that I myself have spend some time to refine to a good solution.
I came out with:
$('#filesToUpload').change(function(e) {
$.each(e.currentTarget.files, function(i, file: File){
var xhr = new XMLHttpRequest();
xhr.onprogress = function (event) {
'do something'
};
xhr.onloadend = function(event){
var status = (<XMLHttpRequest>event.target).status;
if (status != 200) {
console.error(String.format("Server did not return a 200 but: {0}.", status));
}
else
'upload completed';
}
xhr.open('POST', 'urlpath', true);
xhr.send(file);
});
});
Thsi will upload yout files on every change - but my main purpose by showing this code, is to guide you towards XMLHttpRequest.
If you have large files, there are a technology to chunk up your data, but that takes a bit af work to get up running.

Related

QML using XMLHttpRequest edit JSON file not working

I import a JSON file in my program and I need to read & edit it.
(Only use QML not QT)
Reading part works totally fine , but writing part doesn't.
This is I try to use XMLHttpRequest sending my data to a json file(through qml workerScript)
"qrc:/1122test.json" is the json file's URL in my program
WorkerScript.onMessage = function(message) {
var xhr = new XMLHttpRequest;
xhr.open("POST" , "qrc:/1122test.json");
xhr.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
xhr.onreadystatechange = function(){
console.log("1122state" , xhr.readyState);
if(xhr.readyState == 4){
// console.log("1122state" , xhr.readyState);
}
}
xhr.send(JSON.stringify({"email":"test#user.com" , "response":{"name" : "newName"}} ));
console.log("saveed");
}
and my json file example
{
"email":"hi#user.com" ,
"response": {
"name":"tester"
}
}
Every time I open terminal cat the json file , it remain same("hi#user.com" didn't change to "test#user.com" and so was name part)
I already changed the json file's authority to 777
Every log in java showed but not show any error code.
This bother me for over a week ,
really appreciate any idea !!!

List Files on a server via front-end javascript

A have a folder filled with files accessible to the end user, and am working on a javascript file to parse through them and deliver them as needed. However, rather than manually updating the list, I'd like the javascript to scan the folder and then list iterate through an array of the files in that folder. Is there a decent way in front-end JS to do this? All solutions I've looked into have turned out to be purely for Node.
For example, say I have a folder structure like so...
/ (Web Root)
|__ /Build_a_card
|__ /Cool pictures
|__ /Summer Pictures
summer_dog.gif
smiling_sun.svg
|__ /Winter Pictures
snowman.png
cat.jpg
And then in the javascript I'd run something like
var image_list = get_list("/Cool Pictures");
build_select_list(image_list);
function get_list(folder_to_look_in){
var the_list = ???
return the_list;
}
...
And then, for example, the JS is run, and after some parsing, the user would see...
<select>
<option value="summer_pictures/summer_dog.gif">summer_dog.gif</option>
<option value="summer_pictures/smiling_sun.svg">smiling_sun.svg</option>
<option value="winter_pictures/snowman.png">snowman.png</option>
<option value="cat.jpg">cat.jpg</option>
</select>
In an insane world, since the individual files in the folder are accessible to javascript, hypothetically I could brute-force every single possible file name in the folder and return success on each one:
function get_list(folder){
var list_of_files = {};
var starting_character = 0;
list_of_files = every_single_option({starting_character}, 0, 40, folder)
}
}
function every_single_option(existing_characters, current_depth, max_depth, folder){
this_string = String.fromCharCode(existing_characters);
if (request_url(this_string, folder)){
there_array[this_string] = this_string;
}
var there_array = {}
var i;
if (current_depth < max_depth){
while (i < 127){
let temp_array = there_array;
temp_array[i] = i;
mix_source(there_array, every_single_option(existing_characters, current_depth + 1, max_depth, folder))
}
}
return there_array;
}
function request_url(url, folder){
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "/" + folder + "/" + url);
oReq.send();
}
function mix(source, target) {
for(var key in source) {
if (source.hasOwnProperty(key)) {
target[key] = source[key];
}
}
}
but as mentioned, doing it that way would be insane (both ridiculously slow and very bad code design, resorting to brute-forcing your own website is just dumb.)
but it does hypothetically prove that there's no reason javascript shouldn't be able to just get a directory listing assuming public permissions. Alternatively, I could make some API with the backend that allows fetching a JSON that lists it, but that's requiring backend code for something that's a frontend process. I'm trying to pull this off with something sane and simple, but the question is... how?
(If you insist on posting a jquery way to do this, please also post a non-jquery way as well as there is no jquery available in my environment.)
So, refusing to admit it's impossible, I engineered a solution that works, and requires no API.
That said, the server has to not be actively blocking the javascript from viewing the directory. In other words, the server hasn't turned indexing off, and the directory doesn't have an index.html or equivalent to rewrite any attempt to index, and the server isn't doing some url-rewriting. In other words, this should work in any server environment that doesn't rewrite or block indexes.
Here's a rough draft (still buggy, needs finished):
var request = new XMLHttpRequest();
request.open('GET', '/my/directory/', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var resp = request.responseText;
}
};
request.send();
var directory_listing = resp;
var regexp = /\b((?:[a-z][\w-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’]))/i;
var match, files = [];
while ((match = regexp.exec(resp)) != null) {
files.push(match.index);
}
console.log(files);
Building off lilHar's answer, we can use DOMParser to create a shadow-DOM for the directory page we're accessing, and then use that to find any links we need:
// relative path to the desired directory
const directory = "/DIRECTORY-NAME/";
// selector for the relevant links in the directory's index page
const selector = "LINK SELECTOR";
const request = new XMLHttpRequest();
request.open("GET", directory, true);
request.onload = () => {
// succesful response
if(request.status >= 200 && request.status < 400)
{
// create DOM from response HTML
const doc = new DOMParser().parseFromString(request.responseText, "text/html");
// get all links
const links = doc.querySelectorAll(selector);
console.log("Links:", links);
links.forEach(link => {
// do stuff with the links
});
}
};
request.send();
Is there a decent way in front-end JS to do this?
No. Nor is that a way that isn't decent.
The front end can communicate with the server via HTTP or WebSockets.
Neither of those provides any built-in mechanism for exploring a filesystem.
You need the server to provide an API (e.g. a web service) which provides the information you want.

Adding Datas via Javascript to existing JSON file on Server

I have following problem. I know that this is discussed quiet often, and i tried a lot of possibilities, but none is working up to now.
I have some datas in my javascript file, which i want to add to a already exsiting .json file on my server. I tried to do it the following way, but whenever i open the .json file after calling ajax_get_json(), no new datas are added.
function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open('POST', 'myyjson.json', true);
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded");
var us = document.getElementById("firstname").value;
var msg= document.getElementById("message").value;
hr.onreadystatechange= function(){
if (hr.readyState == 4 && hr.status == 200){
var obj = JSON.parse(hr.responseText);
obj['participant'].push({"user": us, "message": msg});
var sendingObj =JSON.stringify(obj);
}
}
hr.send (sendingObj);
}
My myjson.json File has following structure:
{ "participant":[
{"user":"Steven", "message":" Hey,i m in!"},
{"user":"Tim", "message":" i wrote sth."},
{"user":"lukas", "message":"example"}
]}
Does anyone have an Idea what the problem yould be or is there a better way doing it?
Thanks in advance!
With javascript on client it's not possible to write JSON on server. If that would be possible, that would be kind of bad from the security perspective. You need to write JSON on server with what ever language you are using there (PHP, Java, javaScript). Then you call that server function from client with AJAX for example. It could go like this:
Javascript on client side request for example url www.yourserver.com/writejson.php?u=steven&m=Hi
On server you catch that request and write to JSON file. username is steven and message is Hi.
By the way, you have misunderstood XMLHttpRequest.send method. You are not sending data to be saved on server. You are firing XMLHttpRequest. Here is walkthrough how your code is executed:
function ajax_get_json(){
var hr = new XMLHttpRequest(); // 1.
hr.open('POST', 'myyjson.json', true); // 2.
hr.setRequestHeader ("Content-type", "application/x-www-form-urlencoded"); // 3.
var us = document.getElementById("firstname").value; // 4.
var msg= document.getElementById("message").value; // 5.
hr.onreadystatechange= function(){ // 6.
if (hr.readyState == 4 && hr.status == 200){ // 8. this is called every time XMLHttpRequest state changes
var obj = JSON.parse(hr.responseText); // 9. this is called when XMLHttpRequest is completed and response is gotten
obj['participant'].push({"user": us, "message": msg}); // 10.
var sendingObj =JSON.stringify(obj); // 11.
}
}
hr.send (sendingObj); // 7. sendingObj is undefined

Calling a website and getting JSON information back

I am not too experienced in javascript on using API's and how to call websites and get information back. I have done this before in Java using HTTP objects and more. I am attempting to make an application where a user can type in a company stock name such as APPL and get back a ton of data like gains, losses, changes, etc. This shouldn't be that hard. I have a html/javascript file with an input textbox for the stock name. This part is easy. But after I tack on the stock name to the end of the URL by concatenation I don't know how to make the call and get the JSON information. There are examples of how to do this in other languages in the web page I am using but not for javascript. I am using this link as a tutorial:
http://digitalpbk.com/stock/google-finance-get-stock-quote-realtime
Here is my javascript code so far: Again this is probably really simple to do. Any help on this would be greatly appreciated and is good to know in the future.
script type="text/javascript">
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
var urlEncoded = "http://finance.google.com/finance/info?client=ig&q=NASDAQ:" + textValue.toString();
for (var i = 0, len = urlEncoded.length; i < len; ++i) {
var object = urlEncoded[i];
confirm(object.toString());
}
}
</script>
I just found the following code for using HTTP GET and tried it out but nothing happens when I click the submit button. Any suggestions on what to do or what's wrong???
function httpGet(theUrl)
{
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, false );
xmlHttp.send( null );
return xmlHttp.responseText;
}
Wow, this is turning out to be a lot more work then I had anticipated. Here is the URL string I am using in my code for yahoo finance. I can navigate to it in the browser and it works like a charm. For the life of me I cannot understand why this isn't working.
var urlEncoded = "http://www.finance.yahoo.com/webservice/v1/symbols/" + textValue.toString() + "/quote?format=json";
You could try jQuery, google and download it.
It's a javascript framework that makes things allot simpler .
$.get( "http://yourur.com/file.php?parameter1=value1&parameter2=value2", function( data ) {
//data now contains whatever it loaded from server
console.log("Loaded from server :", data);
}, "json");

How to receive response on client side?

I have this form to upload an xml file to server, I am using fiddler to monitor each req and resp. So the server sends me a small xml and i would like to receive it in my javascript as XMLHttpRequest makes it happen
Note: I am uploading a file so enctype="multipart/form-data"
var client;
var url_action = "/csm/create.action";
var dataString;
if (window.XMLHttpRequest) {
client = new XMLHttpRequest();
} else {
client = new ActiveXObject("Microsoft.XMLHTTP");
}
if (client.readyState == 4 && client.status == 200) {
alert(client.responseTest);
}
client.open("POST", url_action, true);
client.setRequestHeader("enctype", "multipart/form-data");
client.send();
My question is how can i receive the response from server side to JS variable. In the above code XMLHttpRequest i don't think i can send a multipart request (file upload). So any alternative is welcome. Whichever solution provides me a response is good.
Here is what i am doing, to submit the form. Thanks :)
var url_action="/csm/create.action";
$('#mainForm').attr('action', url_action);
$('#mainForm').submit();
Updated with solution
$(data).find('com\\.abc\\.db\\.ConfigInfo').each(function(){
cfgid=$(this).find('cfgId').text();
cfgname=$(this).find('cfgName').text();
filename=$(this).find('fileName').text();
timestamp=$(this).find('updateDate').text();
alert(cfgid+", "+cfgname+", "+filename+", "+timestamp);
});
You have jQuery available so don't ever create XHR objects manually.
Besides that, you cannot use AJAX for file uploads unless you don't care about compatibility with certain browsers.
Last but not least, you want to use the jQuery form plugin which will automatically fallback to a hidden iframe and a regular form if there is a file input in the form.
Note that you need to wrap your JSON response in <textarea></textarea> for it to work properly though. See http://jquery.malsup.com/form/#file-upload for details. If you want to return XML you don't need to wrap it though - it should work fine without any server-side changes.

Categories

Resources