Zip folder with password on node js(meteor/react) - javascript

So that's what I've got:
Client fills input form and send this data to the server. Server creates folder, where it generate JSON file with user data. In the same folder user uploads some files (images).
What do I need:
I need to zip this folder with password from the user sent input form. And send this protected zip file back to the client.
I've found library which make zip from the folder (like this one https://www.npmjs.com/package/zip-dir ) and the library which generates single text file and makes password protected zip from it:
https://www.npmjs.com/package/minizip-asm.js
Guys, I really need help ho to combine this two solutions)) Or maybe
Maybe someone already had such an experience?

I guess I found the solution:
var Minizip = require('minizip-asm.js');
var fs = require("fs");
var mz = new Minizip();
var image = fs.readFileSync('./1.jpg');
var text = new Buffer("Abc~~~");
mz.append("haha/abc.txt", text, {password: "123"});
mz.append("haha/abc2.jpg", image, {password: "123"});
fs.writeFileSync("abc.zip", new Buffer(mz.zip()));

Related

Upload password protected file to server

I am running a Python HTTP server that host a captive portal. Basically I'm trying to upload a password protected file to the server.
Right now I am able to upload files to the server with JavaScript and FileReader. This is how I do it:
var file_cli_cert = document.getElementById(id="exa_cli_cert").files[0];
const xmlhttp1 = new XMLHttpRequest();
let name = file_cert.name;
let reader = new FileReader();
reader.readAsText(file_cert);
xmlhttp1.open("POST", '/load/cert');
reader.onload = function(){
xmlhttp1.send(name +"&CERT="+reader.result);
With non-password protected files this works well.
For password protected files my idea is to get the file and the password to access to the data. The problem is that I don't know how to access to password protected files in JS and i think it's not possible. So right now i am wondering how to send the file and the password to the server and access the file data there.
If I send the file object with XMLHttpRequest.send(), on the server side I get the object in string format.
To read the POST message, in the server side, I do:
ctype, pdict = cgi.parse_header(self.headers['content-type'])
content_len = int(self.headers.get('Content-length'))
post_body = self.rfile.read(content_len) #read credentials
self.send_response(201)
self.end_headers()
if self.path.endswith('/load/cert'): #if user loads a certificate
post_body = post_body.decode()
post_body = post_body.split("&CERT=") #split name and file content
name_cert = post_body[0]
file_content = post_body[1]
f = open("./certs/"+name_cert, "w")
f.write(file_content)
f.close()
I'm a newbie at this and I have been looking for a solution for hours. Any help will be appreciated.
No python expert but reading a encrypted file as Text with FileReader could be problematic as it could lead to some data loss when encoding it as text. You should rather be reading it as binary using reader.readAsArrayBuffer()
But there is no need to read the content of the file into memory and allocate memory, just upload the blob/file directly to the server and it will take care of sending the data from the disc to the network without touching the main javascript thread without any text transformation.
const [ file ] = document.querySelector('#exa_cli_cert').files
fetch('/load/cert', {
method: 'POST',
body: file,
headers: {
'x-file-name': file.name
}
})
.then(r => r.arrayBuffer())

Upload a File from Local Angular Folder to Server

I Have placed four static files in Assets/Image Folder in my Angular 8 app.
User has provision to select one File.
My problem is that, I want to upload the selected file to the server in his own Server Folder.
I tried this
var File = new file( new File(["img1"],"./assets/images/nathure_image1.png");
and send this file to server
public uploadImage(fileToUpload: File): Observable<any> {
const formData: FormData = new FormData();
formData.append('fileKey', fileToUpload, fileToUpload.name);
return this.http.post(this.appSettings.API_Config + this.controllerName + '/uploadImage', formData);
}
but it is wrong it create new file and not sends already existing File
Please let me know if my question is unclear ,
I can help with more details
I just want to send my existing client file to serve through API
Thanks for any help

check uploaded file format on client side

I am creating a web portal where end user will upload a csv file and I will do some manipulation on that file on the server side (python). There is some latency and lag on the server side so I dont want to send the message from server to client regarding the bad format of uploaded file. Is there any way to do heavy lifting on client side may be using js or jquery to check if the uploaded file is "comma" separated or not etc etc?
I know we can do "accept=.csv" in the html so that file extension has csv format but how to do with contents to be sure.
Accessing local files from Javascript is only possible by using the File API (https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications) - by using this you might be able to check the content whether it matches your expectations or not.
Here's some bits of code I used to display a preview image clientside when a file is selected. You should be able to use this as a starting point to do something else with the file data. Determining whether its csv is up to you.
Obvious caveat:
You still have to check server side. Anyone can modify your clientside javascript to pretend a bad file is good.
Another caveat:
I'm pretty sure that you can have escaped comma characters in a valid csv file. I think the escape character might be different across some implementations too...
// Fired when the user chooses a file in the OS dialog box
// They will have clicked <input id="fileId" type="file">
document.getElementById('fileId').onchange = function (evt) {
if(!evt.target.files || evt.target.files.length === 0){
console.log('No files selected');
return;
}
var uploadTitle = evt2.target.files[0].name;
var uploadSize = evt2.target.files[0].size;
var uploadType = evt2.target.files[0].type;
// To manipulate the file you set a callback for the whole contents:
var FR = new FileReader();
// I've only used this readAsDataURL which will encode the file like data:image/gif;base64,R0lGODl...
// I'm sure there's a similar call for plaintext
FR.readAsDataURL($('#file')[0].files[0]);
FR.onload = function(evt2){
var evtData = {
filesEvent: evt,
}
var uploadData = evt2.result
console.log(uploadTitle, uploadSize, uploadType, uploadData);
}
}

How to serve static files in node.js after renaming them?

I am creating a node.js app in which user can upload files and can download later.
I am storing file information (original file name that user uploaded, ...) in mongodb document and named that file same as mongodb document id. Now i want my user to be able to download that file with the original file name.
What i want to know is when a user sends a GET request on http://myapp.com/mongoDocument_Id
user gets a file named myOriginalfile.ext
I know about node-static and other modules but i can't rename them before sending file.
i am using koa.js framework.
Here's a simple example using koa-file-server:
var app = require('koa')();
var route = require('koa-route');
var send = require('koa-file-server')({ root : './static' }).send;
app.use(route.get('/:id', function *(id) {
// TODO: perform lookup from id to filename here.
// We'll use a hardcoded filename as an example.
var filename = 'test.txt';
// Set the looked-up filename as the download name.
this.attachment(filename);
// Send the file.
yield send(this, id);
}));
app.listen(3012);
In short:
the files are stored in ./static using the MongoDB id as their filename
a user requests http://myapp.com/123456
you look up that ID in MongoDB to find out the original filename (in the example above, the filename is just hardcoded to test.txt)
the file ./static/123456 is offered as a download using the original filename set in the Content-Disposition header (by using this.attachment(filename)), which will make the browser store it locally as test.txt instead of 123456.

Accessing FTP through netsuite

I want to schedule a script on NetSuite to upload and download a txt file from an FTP location. I am able to create a file and store it in a file cabinet but that is as far as I can go.
I am a bit new and don't know if at all is it possible to have FTP scheduled from NetSuite?
Unfortunately, there is no FTP access to NetSuite.
You can work around that limitation with a scheduled script or web services however.
Here is a previous post with example code on how to start a scheduled script: How to upload a file to Netsuite File Cabinet Automatically?
Place your CSV file into a location that is publicly visible(obviously, this only works if it's not sensitive information! PLEASE PLEASE PLEASE don't do this if you don't want the whole world to see it!)
Create a scheduled script in NetSuite. Set the deployment to run daily, at whatever time you deem best
In your scheduled script, use nlapiRequestUrl (NS help doc) to get the file from wherever you placed it (Note that there is a 5mb size limitation!)
Use nlapiCreateFile (NS help doc) to create a file
Use nlapiSubmitFile (NS help doc) to submit it to the file cabinet
Sample code:
var response = nlapiRequestURL('http://yourserver.yourcompany.com/somecsvfile.csv');
var csvDataInBase64 = response.getBody();
var file = nlapiCreateFile('mycsv.csv', 'CSV', csvDataInBase64);
nlapiSubmitFile(file);
There is no error checking or anything in that sample, but it should get you started.
In SuiteScript 2.0 you can upload/download to SFTP locations using the N/sftp module. Here is a snippet of code I have used for a customer.
var csvfile = file.create({
'name': 'transactions.csv',
'fileType': file.Type.CSV,
'contents': filecontents
});
var conn = sftp.createConnection({
'username': username,
'passwordGuid': passwordGuid,
'url': url,
'directory': directory,
'hostKey': hostkey
});
conn.upload({
'file': csvfile,
'replaceExisting': true
});

Categories