I want to change the .name of an uploaded filein Vue.js - html

So I have this file input where the user selects an image. But once I have this image, I want to change ONLY the name, so for example, user uploads "wallpaper_hd_dragonball_z.jpg" and I want it to be named "wallpaper.jpg". This is the input:
<input type="file" #change="uploadImage($event,userDetails.email)">
And this is the function it calls to store the image in the database:
uploadImage(e, email){
this.selectedFile = e.target.files[0];
console.log(this.selectedFile.name);
var storageRef = firebaseApp.storage().ref(`profilePics/${email}/${this.selectedFile.name}`);
const task = storageRef.put(this.selectedFile);
task.on('state_changed',snapshot=>{
let percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
this.uploadValue = percentage;
}, error=>{console.log(error.message)},
()=>{this.uploadValue=100;
task.snapshot.ref.getDownloadURL().then((url)=>{
this.picture = url;
console.log(this.picture);
})
})
}
Basically what I'm trying is:
this.selectedFile.name = "profPic.jpg";
console.log(this.selectedFile.name);
But it doesn't work. I've looked around google and I can't find how to do it.

You don't have to change the name of the file you have in memory, because the name property of a File object is read-only.
Instead, just rename the file you will save in Firebase Storage.
function getFileExtension(fileName) {
return filename.split('.').pop();
}
//...
const fileExtension = getFileExtension(this.selectedFile.name);
var storageRef = firebaseApp.storage().ref(`profilePics/${email}/wallpaper.${fileExtension}`);
storageRef.put(this.selectedFile);
// ...
Or create a new file object, with another name.
const myNewFile = new File([this.selectedFile], 'wallpaper.png', {type: myFile.type});
firebaseApp.storage().ref(`profilePics/${email}/${myNewFile.name}`);
storageRef.put(myNewFile);
// ...

Related

create file object using file path instead of input file form

most if not all Forge samples used input file form to get input file like below:
$("#inputFile").change(function () {
_fileInputForm = this;
if (_fileInputForm.files.length === 0) return;
var file = _fileInputForm.files[0];
}
what if i want to achieve the same result without UI at all? something like below:
const data = {
ModelId: "dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLjNSTzhMWmtUVGVHM3p1M1FoNjRGM3c_dmVyc2lvbj0x",
ElementId: [{ UniqueId: "ca5762b5-0f46-4a2f-8599-1d1a5dd19a81-00024b8c" }],
};
var file = new File([data], "whatever.json", { type: "application/json" });
data is manually copied from whatever.json, how to do it via code? thanks

How to load file after being uploaded (not saved in database yet) in angular, html

I have a file upload control in my angular app where user could upload any type of file except a few ones .exe, .sql etc
<input type="file" id="file" #file (change)="fileUploadHandler($event)" multiple>
fileupload.component.ts
fileUploadHandler(event: Event) {
const inputElement = event.target as HTMLInputElement;
if (inputElement.files && inputElement.files?.length) {
_each(inputElement.files, (_file) => {
const fileSize = _file.size;
if (fileSize < this.MAX_DOC_SIZE) {
const fileName = _file.name?.trim();
const doc = new Document();
doc.name = fileName;
doc.extension = fileName.slice(fileName.lastIndexOf('.') + 1);
doc.size = fileSize;
this.docs.push(doc);
}
});
}}
This list the files in UI as below
Now what I need is that when user click on a file, that file should open in a new tab
how can I do this?
On googling I see suggestions to use FileReader & gave a try
_each(inputElement.files, (_file) => {
const reader = new FileReader();
const data = reader.readAsDataURL(_file);
console.log(data) // nothing is printed on console
Please suggest. Thanks!
You have to enhance the code a little bit (as #mav-raj also stated). In Angular you can use the following:
_each(inputElement.files, (_file) => {
const reader = new FileReader();
reader.onloadend = ((result) => {
console.log(result) // now something will be printed!
});
reader.readAsDataURL(_file);
})

Using a service in Jhipster to populate a second entity with user uploaded CSV BLOB entity

I am new to Jhipster and trying to create a basic app that will allow a user to upload a CSV file and then view the contents in an entity.
I am trying to figure out a way to populate a second entity with the data contained in a CSV blob that will be uploaded by the user. I have created an entity that allows the user to upload a CSV file and store it in the database as a BLOB, and I have also created a service with the intention of populating a second entity with records based on the contents of the CSV file that was uploaded.
How would I go about this? I have used OpenCSV in the past to read CSV files and populate MySQL tables via their filepath, but I am unfamiliar with accessing CSV files that are stored in the database as a BLOB.
I implemented same use case using supercsv but I don't store the csv in blob: in service I parse the DTO from controller and stores resulting entities, in the blob I store the errors if any. It's a bit abusive but it works well and the entity to create the other one is just a way to record how upload went, this way I can reuse the UI generated by JHipster without any change.
1.in html:
</td>
<td style="padding: 5px;">
<input type="button"
name="Reset"
id="txtFileReset"
class="btn btn-primary"
(click)="csvReset()"
value="Reset"/>
<input type="button"
name="Reset"
id="txtFileSave"
class="btn btn-primary"
(click)="csvSave()"
value="Save CSV To DB"/>
</td>
2.in ts:
csvRecords = [];
fileChangeListener($event): void {
const text = [];
const target = $event.target || $event.srcElement;
const files = target.files;
if (Constants.validateHeaderAndRecordLengthFlag) {
if (!this.fileUtil.isCSVFile(files[0])) {
alert('Please import valid .csv file.');
this.csvReset();
}
}
const input = $event.target;
const reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = data => {
const csvData = reader.result;
const csvRecordsArray = csvData.split(/\r\n|\n/);
let headerLength = -1;
if (Constants.isHeaderPresentFlag) {
const headersRow = this.fileUtil.getHeaderArray(csvRecordsArray, Constants.tokenDelimeter);
headerLength = headersRow.length;
}
this.csvRecords = this.fileUtil.getDataRecordsArrayFromCSVFile(
csvRecordsArray,
headerLength,
Constants.validateHeaderAndRecordLengthFlag,
Constants.tokenDelimeter
);
if (this.csvRecords === null) {
// If control reached here it means csv file contains error, reset file.
this.csvReset();
}
};
reader.onerror = function() {
alert('Unable to read ' + input.files[0]);
};
}
csvReset() {
this.elementRef.nativeElement.querySelector('#txtFileUpload').value = '';
this.csvRecords = [];
}
csvSave() {
this.ipInfo = new IpInfoSdmSuffix();
for (let i = 1; i < this.csvRecords.length; i++) {
this.ipInfo.name = this.csvRecords[i][0];
this.ipInfo.addressStart = this.csvRecords[i][1];
this.ipInfo.addressEnd = this.csvRecords[i][2];
this.ipInfo.validType = this.csvRecords[i][3];
this.subscribeToSaveResponse(this.ipInfoService.create(this.ipInfo));
}
}
private subscribeToSaveResponse(result: Observable<HttpResponse<IIpInfoSdmSuffix>>) {
result.subscribe((res: HttpResponse<IIpInfoSdmSuffix>) => this.onSaveSuccess(), (res: HttpErrorResponse) => this.onSaveError());
}
private onSaveSuccess() {
this.isSaving = false;
this.isCsvSaved = false;
// this.previousState();
this.clear();
}
private onSaveError() {
this.isSaving = false;
this.isCsvSaved = false;
}

Creating a zip file from a JSON object using adm-zip

I'm trying to create a .zip file from a JSON object in Node.js. I'm using adm-zip to do that however I'm unable to make it work with this code:
var admZip = require('adm-zip');
var zip = new admZip();
zip.addFile(Date.now() + '.json', new Buffer(JSON.stringify(jsonObject));
var willSendthis = zip.toBuffer();
fs.writeFileSync('./example.zip', willSendthis);
This code creates example.zip but I'm not able to extract it, I tried with a .zipextractor but also with this code:
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.data.toString('utf8'));
});
It returns Cannot read property 'toString' of undefined at the line with console.log.
I could use zip.writeZip() for this example but I'm sending the .zipfile to Amazon S3 thus I need to use the method .toBuffer() to do something like this after using adm-zip:
var params = {Key: 'example.zip', Body: zip.toBuffer()};
s3bucket.upload(params, function(err, data) {...});
I don't see what is wrong, am I using the package correctly?
Try use zipEntry.getData().toString('utf8') instead zipEntry.data.toString('utf8'):
var admZip = require('adm-zip');
var zip = new admZip("./example.zip");
var zipEntries = zip.getEntries(); // an array of ZipEntry records
zipEntries.forEach(function(zipEntry) {
console.log(zipEntry.getData().toString('utf8'));
});

File field - Append file list

I have made me a simple file field:
<input type="file" name="pictures_array[]" multiple accept="image/*" id="page_pictures_array" />
and some HTML5 File API code to list the files:
$('.page-form #page_pictures_array').change(function(evt) {
var file, files, reader, _i, _len;
files = evt.target.files;
console.log(files);
$('#file-list').empty();
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
reader = new window.FileReader;
reader.onload = (function(file) {
return function(e) {
var src;
src = e.target.result;
return $("<li>" + file.name + " - " + file.size + " bytes</li>").prepend($('<img/>', {
src: src,
"class": 'thumb'
})).appendTo($('#file-list'));
};
})(file);
reader.readAsDataURL(file);
}
});
(cf. here)
However, since I expect my users to be very stupid indeed, I am sure they will choose one file, then click on the upload field another time to choose the next. However, the list of the <input type="file"> is reset each time with the newly chosen images.
How can I make sure the new files are appended to the <input>'s array so I don't get flooded with angry user comments?
I'm also looking for an answer to this, I think others already do that.
But if you look at the filelist W3 reference http://www.w3.org/TR/FileAPI/#dfn-filelist it says that its readonly....
Edit: It's a big code now, with some improvements, that make the copy/paste difficult. But I started to create one variable that saves all the tmp files.
var tmp_files = new Array();
Then when I add a new file I push the file to that array like this
tmp_files.push(file);
After all the insertions/removals (I have another var to save the deletions) when the user clicks to send the files I have this code that makes the formdata with the files I want
var data = new FormData(); var count = 0;
$.each(tmp_files, function(i, file){
if(del_files.indexOf(file.name)== -1){
data.append(count, file);
count++;
}
});
Then I just send the var data thru ajax and save them.
You can get them using $data = $_FILES;
Hope this helps you.