How to dynamically populate files in multiple file input - javascript

I'm using a JavaScript lib here to select multiple image and save them in database through a form, and when i edit the form i get the images from data and populate like this.
<script>
var upload = new FileUploadWithPreview('myUniqueUploadId', {
showDeleteButtonOnImages: true,
text: {
chooseFile: 'Įkelkite nuotrauką',
browse: 'naršyti',
selectedCount: 'Pasirinkti failai',
},
presetFiles: [
<?php
foreach($Workimages as $Workimg){
echo $website_url.'master_image/'.$Workimg.','
}
],
})
</script>
The Images are coming as Blob and are being populated but when i update the data in database the old images are disregard but the new selected images get uploaded. I also checked $_FILES['images']. it don't have my old image files.
I have also tried to used methods upload.cachedFilesArray.push and upload.addFiles() but i wasn't successful at that. Is there any other way to populate multiple file input?

I'm the author of this library.
It seems as though you've uncovered a problem with a Blob type being accepted by your PHP server. This may be something that I just never ran into before, because I feel like I've uploaded Blob types in the past to my PHP servers - but maybe I'm just imagining things and they've always been File types and that's why I never had any issue.
Regardless, to make your situation work in the meantime, I made a simple codepen that loops over the upload.cachedFileArray array and converts each Blob (or File) into a File type, and appends it to a new temp array that's ready for uploading. See the comments in the codepen for more.
At this point, you can just upload the new temp array and you'll be all set. In the future I'll look at making sure all the presetFiles are of the type File instead of Blob.

Related

How to filter out non-json documents in MarkLogic?

I have a lot of data loaded in my database where some of the documents loaded are not JSON files & just binary files. Correct data looks like this: "/foo/bar/1.json" but the incorrect data is in the format of "/foo/bar/*". Is there a mechanism in MarkLogic using JavaScript where I can filter out this junk data and delete them?
PS: I'm unable to extract files with mlcp that have a "?" in the URI and maybe when I try to reload this data I get this error. Any way to fix that extract along with this?
If all of the document URIs contain a ? and are in that directory, then you could use cts.uriMatch()
declareUpdate();
for (const uri of cts.uriMatch('/foo/bar/*?*') ) {
xdmp.documentDelete(uri)
}
Alternatively, if you are looking to find the binary() documents, you can apply the format-binary option to a cts.search() with a cts.directoryQuery() and then delete them.
declareUpdate();
for (const doc of cts.search(cts.directoryQuery("/foo/bar/"), ['format-json']) ) {
xdmp.documentDelete(fn.baseUri(doc));
}
They are probably being persisted as binary because there is no file extension when the URI ends with a question mark and some querystring parameter values i.e. 1.json?foo=bar instead of 1.json
It is difficult to diagnose and troubleshoot without seeing what your MLCP job configs are and knowing more about what you are doing to load the data.

CKEditor Plug-In: Getting text of drop-down item

I created a plug-in for CKEditor that opens a dialog with a drop-down. In that drop-down is a list of files the user has uploaded outside of CKEditor. The plan is to insert a "tag" into the text containing that filename, something like [[myfile.pdf]] and then when I display the actual page, I will insert a link to that file.
The problem is that the drop-down box being created by CKEditor is listing the filename (properly) but when I select it, it inserts the file's SIZE into the text rather than the filename. When the plug-in runs, it does an ajax call and grabs a directory listing of the user's files, which is where that number comes from; I think it's confusing it with a file ID.
Here's the meat of the plug-in. I left out the ajax call for brevity. It populates the variable "items."
EDIT: I modified the results returned from the ajax call to just return the filename, and then to return the filename (twice) using two different column names (name and filename) and in both cases, the inserted value was NULL. It just doesn't want to insert a text value it seems.
I also tried changing the values of id: under contents and also under elements (alternately) between tab-basic and linkType, and I got an error in the JS console about cannot read property getValue of undefined. Curses, foiled again!
ANOTHER EDIT: I tried putting the names of the files in a database table and I return that to the plug-in instead of the directory listing. If I select filename, attachmentid (in that order), the OPTION box lists the attachmentid, and inserts the filename. If I select attatchmentid, filename it will do it the exact opposite. So then I thought, gee, what if I selected the filename twice? So I did select filename, filename as filename2. And it works! This still isn't an ideal solution so I'm hoping somebody will know the proper way to do it.
CKEDITOR.dialog.add('attachfileDialog',function(editor){
return {
title:'Attach File',
minWidth:400,
minHeight:200,
contents:[{
id:'tab-basic',
label:'Choose File',
elements:[{
type:'select',
id:'linkType',
label:'Choose File',
items:items,
'default':''
}]
}],
onOk:function(data){
var dialog = this;
var componentType = dialog.getValueOf('tab-basic','linkType');
var selectedText = editor.getSelection().getSelectedText();
if(componentType != ''){
editor.insertText('[[' + componentType + ']]');
}
}
};
});
I actually copied this from another plug-in and modified it to suit, so I'll admit I don't much know what I'm doing here. I've dug through the CKEditor docs but they aren't particularly helpful.
The variable componentType is coming back with the file size. I'm just not sure how to make it grab the text instead of the value; if you view the source, the has the value of the file size, and the text is the filename.
Any ideas? Thank you!

How can I save the array of input type file in storage location?

Hi i want to save the array of an input type file.
<input type="file" id="fuGerber" onchange="saveFiles(this.files)" multiple />
I already tried this:
localStorage.setItem('files',JSON.stringify(files));
OR this:
localStorage.setItem('files',JSON.stringify(files[0]));
but JSON.stringify returns empty "{}" or this in the second case "{"0":{}}"
Does any one knows something to save it without lose nothing inside of the array.
This is what my array have:
Maybe you're missing using a file reader to actually read the data from the file input which you can then store in an array before you save it to localStorage.
See this answer here.
Update:
So I finally realized what you were having trouble with after duplicating the issue in JSFiddle. The problem is FileList is NOT an array (see here), it's a custom list type. As a result the JSON encoder doesn't know how to encode properly.
To get the data from the FileList you have to manually create a file object of each File in the FileList, push each object to an array\, and then you will be able to stringify and set to localStorage.
Doing the above I was able to successfully save the files:
View of files array in localStorage
See my code example:
JSFiddle
Cheers! I hope this helps :)
If you are trying save an array do this:
To save:
localStorage.setItem('files', JSON.stringify(files));
To recovery from localStorage:
value = localStorage.getItem('files');
result = JSON.parse(value);
Updated:
For a file check this link
How to save an image to localStorage and display it on the next page?

Convert base64 image to file in javascript or how to pass a big base64 string with jquery ajax

This can't take any more of my time. I've tried to solve this a very long time now.
I will give you my whole scenario and then what the problem is.
I have this web site. On one page the user can choose between three image input types.
This is a radio button group:
o Twitter Logo
o Twitter Profile Picture
o Upload picture
If the user choose option 1 or 2, an img tag src is updated with a local-project file (http://localhost:9000/public/images/image.png) and this image src is stored in html5 Web Session Storage variable.
If the user choose option 3 he/she get to choose a file from their computer (a input type="file" appears under the radio group) and the img tag src is updated with this image.
This time, the src that I will store in the session variable won't be a path to the file (which I know is because of security reasons) but the src will be a base64 string. A really big one if the user choose a big image.
So now I have this image stored in the session variable, either a path to the image file included in the project folder or a base64 encoded image.
What I do now is to fetch this value from the session variable in JavaScript. I want to pass this image to my code on the server side. For making an actual image of it and uploading it to places, but that part isnt really necessary.
My problem is that in JavaScript, I can't pass this with a POST using $.ajax.
The base64 string is too big I think, and I can't figure out how I can convert it to something else, say a byte[].
How should I do?
I want to pass this image that the user choose to the server side for further process.
Then on the server side I want to convert it to an actual Image object, or BufferedImage.
Here's a code-block of how it looks now:
function gatherSessionValuesAndGenerateCode(userEmail) {
var email = userEmail;
var category = getSessionValue("category");
var itemName = getSessionValue("itemName");
var service = getSessionValue("service");
var accountName = getSessionValue("accountName");
var action = getSessionValue("action");
var imageType = getSessionValue("imageType");
var imageFile = getSessionValue("imageFile");
var expirationDate = getSessionValue("expirationDate");
$.ajax({
type: "POST",
url: "http://localhost:9000/quikkly/business/create/generate",
data: {
email: email,
category: category,
itemName: itemName,
service: service,
accountName: accountName,
action: action,
imageType: imageType,
imageFile: imageFile, //This is making me feel ill, don't know how to solve it.
expirationDate: expirationDate
},
success: function(response){console.log("Horayyy "+response)}
});
}
ok i got your point but what i am trying to say is may be your string contains 20K characters but i don't think it can be larger than 2-3 Mb and i hope your server settings allows you to post data of size of 2-3 MB.
Apart from this i think putting the image path name in base_64 is not a good idea.If you think someone can steel the data from your seesion then he/she can do any thing with your complete website concept.
Because any how a person can see the image path even when you display some image over web page.
Still if you think you don't want path in seesion you can keep it in some file in key-value pair or you can keep it in database.
OR you can do one more thing just keep the image file name in your seesion data & prepend the exact path when you want to use it internally over server side.

How go I get csv data into netsuite?

I've got an update to my question.
What I really wanted to know was this:
How do I get csv data into netsuite?
Well, it seems I use the csv import tool to create a mapping and use this call to import the csv nlapiSubmitCSVImport(nlobjCSVImport).
Now my question is: How do I iterate through the object?!
That gets me half way - I get the csv data but I can't seem to find out how I iterate through it in order to manipulate the date. This is, of course, the whole point of a scheduled script.
This is really driving me mad.
#Robert H
I can think of a million reasons why you'd want to import data from a CSV. Billing, for instance. Various reports on data any company keeps and I wouldn't want to keep this in the file cabinet nor would I really want to keep the file at all. I just want the data. I want to manipulate it and I want to enter it.
Solution Steps:
To upload a CSV file we have to use a Suitelet script.
(Note: file - This field type is available only for Suitelets and will appear on the main tab of the Suitelet page. Setting the field type to file adds a file upload widget to the page.)
var fileField = form.addField('custpage_file', 'file', 'Select CSV File');
var id = nlapiSubmitFile(file);
Let's prepare to call a Restlet script and pass the file id to it.
var recordObj = new Object();
recordObj.fileId = fileId;
// Format input for Restlets for the JSON content type
var recordText = JSON.stringify(recordObj);//stringifying JSON
// Setting up the URL of the Restlet
var url = 'https://rest.na1.netsuite.com/app/site/hosting/restlet.nl?script=108&deploy=1';
// Setting up the headers for passing the credentials
var headers = new Array();
headers['Content-Type'] = 'application/json';
headers['Authorization'] = 'NLAuth nlauth_email=amit.kumar2#mindfiresolutions.com, nlauth_signature=*password*, nlauth_account=TSTDRV****, nlauth_role=3';
(Note: nlapiCreateCSVImport: This API is only supported for bundle installation scripts, scheduled scripts, and RESTlets)
Let's call the Restlet using nlapiRequestURL:
// Calling Restlet
var output = nlapiRequestURL(url, recordText, headers, null, "POST");
Create a mapping using Import CSV records available at Setup > Import/Export > Import CSV records.
Inside the Restlet script Fetch the file id from the Restlet parameter. Use nlapiCreateCSVImport() API and set its mapping with mapping id created in step 3. Set the CSV file using the setPrimaryFile() function.
var primaryFile = nlapiLoadFile(datain.fileId);
var job = nlapiCreateCSVImport();
job.setMapping(mappingFileId); // Set the mapping
// Set File
job.setPrimaryFile(primaryFile.getValue()); // Fetches the content of the file and sets it.
Submit using nlapiSubmitCSVImport().
nlapiSubmitCSVImport(job); // We are done
There is another way we can get around this although neither preferable nor would I suggest. (As it consumes a lot of API's if you have a large number of records in your CSV file.)
Let's say that we don't want to use the nlapiCreateCSVImport API, so let's continue from the step 4.
Just fetch the file Id as we did earlier, load the file, and get its contents.
var fileContent = primaryFile.getValue();
Split the lines of the file, then subsequently split the words and store the values into separate arrays.
var splitLine = fileContent.split("\n"); // Splitting the file on the basis of lines.
for (var lines = 1,count=0; lines < splitLine.length; lines++)
{
var words = (splitLine[lines]).split(","); // words stores all the words on a line
for (var word = 0; word < words.length; word++)
{
nlapiLogExecution("DEBUG", "Words:",words[word]);
}
}
Note: Make sure you don't have an additional blank line in your CSV file.
Finally create the record and set field values from the array that we created above.
var myRec = nlapiCreateRecord('cashsale'); // Here you create the record of your choice
myRec.setFieldValue('entity', arrCustomerId[i]); // For example, arrCustomerId is an array of customer ID.
var submitRec = nlapiSubmitRecord(myRec); // and we are done
fellow NetSuite user here, I've been using SuiteScripts for a while now but never saw nlobjCSVImport object nor nlapiSubmitCSVImport .. I looked in the documentation, it shows, but there is no page describing the details, care to share where you got the doc from?
With the doc for the CSVImport object I might be able to provide some more help.
P.S. I tried posting this message as a comment but the "Add comment" link didn't show up for some reason. Still new to SOF
CSV to JSON:
convert csv file to json object datatable
https://code.google.com/p/jquery-csv/
If you know the structure of the CSV file, just do a for loop and map the fields to the corresponding nlapiSetValue.
Should be pretty straightforward.

Categories

Resources