Upload a File from Local Angular Folder to Server - javascript

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

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())

Is it possible to get the foldername for a file uploaded with dropzone.js

I'm using dropzone.js as a part of my flask application, where the user can upload multiple folders at the same time. But sometimes the most valuable information about the files is the folder name.
An example could be:
Folder A
sample.txt
img.png
Folder B
sample.txt
img.png
Would it here be possible to to register which files comes from Folder A and which comes from Folder B, assuming that they drag-n-drop the whole folder into the dropzone?
I figured out how to do this with assistance from this answer and MDN's article on Using FormData objects.
If you define your dropzone like this in the template:
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone("form#my-awesome-dropzone",
{ url: "/upload",
});
You must then add an event handler for the sending event, which takes the file.fullPath string, and adds it to a blob which becomes part of the multipart/form-data submission.
myDropzone.on("sending", function(file, xhr, formData) {
// get the original fullPath and add it to the multipart form.
var blob = new Blob([file.fullPath], { type: "text/plain"});
formData.append("originalPath", blob);
});
Note that this essentially adds a second file called blob with the text/plain mimetype to your form submission. To visualize this, within the upload route on your Flask server, you can print(request.files) which gives:
ImmutableMultiDict(
[('originalPath', <FileStorage: 'blob' ('text/plain')>),
('file', <FileStorage: 'up.txt' ('text/plain')>)
])
So to extract the actual string from that on the server end you could do:
original_path = request.files['originalPath'].read().decode('utf-8')
Note that from the frontend perspective, dropzone doesn't know about parent folders relative to the file or folder that was dropped, so:
dropping a file called up.txt into Dropzone, original_path will be 'undefined'.
dropping a folder called untitled folder containing a file called up.txt into Dropzone, original_path will be 'untitled folder/up.txt'.
You should build some functionality on the backend to validate the info coming in, and parse these strings accordingly.

Send file to PHP server with JS

I can send files from the browser to the server using drag'n'drop and this code simply works fine:
var temp = new FormData();
temp.append("file_content",e.originalEvent.dataTransfer.files[0]);
//Ajax POST here...
Then I make a POST request (Ajax) to send that file to PHP and PHP can manipulate that file using $_FILES[file_content]. Easy.
My problem is that sometimes the user drops a folder and I already can manipulate the files inside that folder with JS in order to send them via Ajax. My problem is that PHP cant manipulate the $_FILE anymore, it is empty. My code:
var reader = entry.createReader();
reader.readEntries(function(entries) {
entries.forEach(function(dir,key) {
if (dir.isFile) {
var temp = new FormData();
temp.append("file_content",dir);
//Ajax POST here...
}
});
});
So I need someway to convert dir (which is of type FileEntry) to type File (e.originalEvent.dataTransfer.files[0]). How can I do this?

File not opening after download: ReactJs + Spring Boot

I am developing a web application and one of my use cases is for users to have the ability to upload and download files from the server. I'm using ReactJs and Spring Boot.
Front-End code:
downloadFileClicked(id, fileName, fileType){
TestDataService.downloadFile(id)
.then(response=>{
console.log(response)
const file = new Blob(
[response.data],
{type: fileType}
)
let url = window.URL.createObjectURL(file)
let a = document.createElement('a')
a.href=url
a.download= fileName
a.click()
})
}
Back-End code:
#GetMapping("/downloadFile/{fileId:.+}")
public ResponseEntity<Resource> downloadFile(#PathVariable Long fileId, HttpServletRequest request ){
//Load file as a resource
DatabaseFile databaseFile = fileStorageService.getFile(fileId);
return ResponseEntity.ok()
.contentType(MediaType.parseMediaType(databaseFile.getFileType()))
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\""+databaseFile.getFileName()+"\"")
.body(new ByteArrayResource(databaseFile.getData()));
}
When the user clicks download - the file does indeed download and seemingly in the correct format but when each application tries to open the file I am faced with such errors as the file format is not supported or the file is corrupt.
The file data is being stored as a byte array in a MySQL database. I have tried a number of different methods to download the file but I have encountered the same error each time. Any help would be greatly appreciated!

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

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()));

Categories