I'm reading the content of a CSV file in the file cabinet with a user Event Suitelet living on sales orders and trying to reset the content of the file to an empty CSV after I'm done
I can successfully append lines and read the content but nothing about resetting the content in the NetSuite documentation.
I'm just looking for a way to reset the File to an empty CSV.
/**
*
#NApiVersion 2.x
#NModuleScope SameAccount
#NScriptType UserEventScript
#appliedtorecord salesorder
*/
define(['N/file'], function(file) {
function resetCSVFile(context) {
var fileObj = file.load({ id: '104819' });
var iterator = fileObj.lines.iterator();
var idArrays = [];
iterator.each(function(line) {
idArrays.push(line.value);
// the line below is my failed attempt at resetting the line
line.value = ''
return true;
});
log.audit({ title: 'idArrays', details: idArrays });
fileObj.save();
return true;
}
return {
afterSubmit: resetCSVFile
};
});
After you're done processing the file, you'll want to use file.create() to make a new file object with the same name, fileType, and folder property values. Set the contents property of that file object to something (perhaps the header row), and save it. This will overwrite the existing file with an empty file but keep the same internal id of the original file.
Here's an example that captures the header row of the CSV file and creates an empty file with that header row. When you create a file object, the contents property cannot be null or an empty string.
var fileObj = file.load({ id: '5447' });
var currentLine = 0;
var headerRow = '';
fileObj.lines.iterator().each(function(line) {
currentLine++;
if (currentLine === 1) {
headerRow = line.value + '\n';
}
log.debug({ title: 'header', details: line.value });
return true;
});
var newFile = file.create({
name: fileObj.name,
fileType: file.Type.CSV,
folder: fileObj.folder,
contents: headerRow
});
newFile.save();
Related
I have an ajax function where I post multiple files in an array. How can store these files? I tried the following code in controller but only the first file is being stored.
foreach ($request->photos as $imagefile) {
$imageName = $imagefile->getClientOriginalName();
$imagePath = public_path('folder-path/');
$imagefile->move($imagePath,$imageName);
}
also this is how my array looks like
array from ajax
as #innovin requested.
Blade File
<input name="files[]" type="file" class="form-control" accept="image/png, image/jpeg" multiple id="files">
Update
function otherUpload(){
var outputdata = [];
var fileSelect = document.getElementById('files');
var files = fileSelect.files;
var formData = new FormData();
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('photos[]', file, file.name);
}
$.ajax({
type: "POST",
url: 'post-url',
contentType: false,
processData: false,
dataType:'json',
data: formData,
success:function(data) {
if(data.code == 1){
console.log(data);
fetchOtherImages();
}
}
});
}
</script>```
you should loop through $request->file('photos') instead of $request->photos
if($request->hasfile('photos'))
{
foreach($request->file('photos') as $photo)
{
$name = $photo->getClientOriginalName();
$file->move(public_path('folder-path'), $name);
// to store file in Storage folder:
//$file->storeAs('files', $name);
}
}
note that he function GetClientOriginalName() is used to retrieve the file's original name at the time of upload in laravel, and that'll only be possible if the data is sent as array and not as a string. Hence, you must add enctype="multipart/form-data" whenever you are creating a form with input fields for files or images.
I have an image source , i need to convert it into png file and append it to backend and send. upload is successfull ,but when we retrieve the stored file from backend , it has invalid file format error. I think it was not converted to base64 and because of this we have this issue. I am using $base64 dependency to covert my source.
source = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAMgAAADICAYAAACtWK6eAAAgAElEQVR4Xjy9Z6xlaXYdts6999ycc3o5p6pXVV3V1Xl6unt62CI5nCFFw6RoyIZtSDIMWTb8wyBk2DBgyYZ/CIT+SJRJGDJNWrboiRRnunu6OR0qp5fq5XRzzjkcY+03ozcoVNebV/eee8639157rbV3Kf/kj35XazbbsFrtqJSa2Ns9Qj5XQa8LOOw+mE0O1Kt9WCxOVCtN5HMlmMx=="
$scope.uploadFile = function(source){
var imageBase64 = $base64.encode(source);
var blob = new Blob([imageBase64], {
type: 'image/png'
});
var filename = Math.random().toString(36).substring(7);
var file = new File([blob], filename + '.png',{type:'image/png'});
$scope.file = file;
var json = {
"json": {
"request":{
"servicetype":"4",
"functiontype": "4012",
"session":{
"sessionid":session
}
}
}
};
fileUpload.uploadFileToEmp( json, file ).then(function(res){
}
}
});
}
So i recently found this google drive script and tried to use it.
The script should normally get file names and url on my google drive folder and copy them in a spreadsheet.
When i click Run, I get no error and nothing happens in my drive.
Is there variables i should change to make it work ?
PS : I'm very new to coding and can't seem to find what is wrong with this code
Thanks in advance for your help !
Here is the code :
function myFunction() {
function listFilesInFolder(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
niceFileType( file.getMimeType() )
];
sheet.appendRow(data);
}
}
}
Two issues. This needs to be ran in a script attached to a spreadsheet and you have a nested function.
Your code:
function myFunction() {
function listFilesInFolder(foldername) {
...
}
}
remove the outer function decleration and its matching closing bracket. The code will run.
It should look like:
function listFilesInFolder(foldername) {
...
}
Try this modified code in spreadsheet instead:
function myfunction(){
//Declaring the function listFolders to temp
var temp = function listFolders(foldername) {
// If we have not been provided a foldername, assume we will interact with user.
var interactive = (typeof foldername === 'undefined');
// Get name of folder to list
if (interactive) {
foldername = Browser.inputBox("List files in folder", "Enter folder name", Browser.Buttons.OK_CANCEL);
}
if (foldername === '') return; // No name provided, exit quietly
var folders = DriveApp.getFoldersByName(foldername);
if (!folders.hasNext()) {
if (interactive) Browser.msgBox("Folder not found.");
return;
}
var folder = folders.next();
var contents = folder.getFiles();
var file, data, sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", /*"Download",*/ "Description", "Type"]);
// Loop over files in folder, using file iterator
while (contents.hasNext()) {
file = contents.next();
if (file.getMimeType() == MimeType.GOOGLE_SHEETS) { // "SPREADSHEET"
// Skip displaying spreadsheets - I don't know why...
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getSize(),
file.getUrl(),
//"https://docs.google.com/uc?export=download&confirm=no_antivirus&id=" + file.getId(),
file.getDescription(),
file.getMimeType()
];
sheet.appendRow(data);
}
}
// calls the function listFolders below
temp()
}
I am using datatables to print the csv file data. The CSV file consists of data .this is an exmple data file.
name,city,category,discount
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
surya,gnt,all,10%
I want to skip first line of data . How to stop displaying th first line in my datatable. And my code is`
//saving csv file to firebase
$('#save-csv').bind('click', function() {
if (window.File && window.FileReader && window.FileList && window.Blob) {
var file = document.getElementById('files').files[0];
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var data = $.csv.toArrays(csv);
var csvObj = {}
for(key in data){
csvObj[key] = {};
csvObj[key].name = data[key][0];
csvObj[key].city = data[key][1];
csvObj[key].category = data[key][2];
csvObj[key].discount = data[key][3];
}
console.log(csvObj);
$scope.csvStores.stores = csvObj;
$scope.csvStores.$save().then(function(res){
console.info(res);
}).catch(function(err){
console.error(err);
});
$("#myModal").modal("hide");
swal(
'Saved',
'Successfully Saved',
'success'
)
}
}else {
}
});
Before you iterate over your data you should somehow remove/skip the first line.
In my opinion it is better to remove, cause if you would like to use later this array, then you have to skip again.
I have two ideas:
before the iteration call:data = data.shift();
based on this: http://www.w3schools.com/jsref/jsref_shift.asp
This will remove the first element.
Or if you are using lodash, than you can easily call data = _.tail(data); based on this: https://lodash.com/docs/4.16.4#tail
I've been trying to figure out how to add a line of text to any type of file using Gulp.
For instance add:
#import 'plugins'
to my main.sass file.
Or add a CDN to an index.html file.
I did try:
gulp.task('inject-plugins', function(){
gulp.src('src/css/main.sass')
.pipe(inject.after('// Add Imports', '\n#import \'plugins\'\n'));
});
with no joy. Any idea how I could achieve this please?
Depends on what you want to do.
If you just want to add text to the beginning or end of a file gulp-header and gulp-footer are your friends:
var header = require('gulp-header');
var footer = require('gulp-footer');
gulp.task('add-text-to-beginning', function() {
return gulp.src('src/css/main.sass')
.pipe(header('#import \'plugins\'\n'))
.pipe(gulp.dest('dist'));
});
gulp.task('add-text-to-end', function() {
return gulp.src('src/css/main.sass')
.pipe(footer('#import \'plugins\''))
.pipe(gulp.dest('dist'));
});
If you have some kind of "anchor" text in your file you can use gulp-replace:
var replace = require('gulp-replace');
gulp.task('replace-text', function() {
var anchor = '// Add Imports';
return gulp.src('src/css/main.sass')
.pipe(replace(anchor, anchor + '\n#import \'plugins\'\n'))
.pipe(gulp.dest('dist'));
});
Finally there's the swiss army knife of vinyl file manipulation: map-stream. This gives you direct access to file contents and allows you to do any kind of string manipulation that you can think of in JavaScript:
var map = require('map-stream');
gulp.task('change-text', function() {
return gulp.src('src/css/main.sass')
.pipe(map(function(file, cb) {
var fileContents = file.contents.toString();
// --- do any string manipulation here ---
fileContents = fileContents.replace(/foo/, 'bar');
fileContents = 'First line\n' + fileContents;
// ---------------------------------------
file.contents = new Buffer(fileContents);
cb(null, file);
}))
.pipe(gulp.dest('dist'));
});