run a function when insert file on sweetAlert - javascript

I'm changing an input file for a button that opens a new window using sweetAlert2
$('#btn-file').on('click', function (){
(async () =>{
let { value: file } = await Swal.fire({
title: 'Select image',
html: 'You can download a model for your work here',
input: 'file',
showCancelButton: true,
inputAttributes: {
'accept': '.csv',
'aria-label': 'Upload your CSV file'
}
})
if (file) {
const reader = new FileReader()
reader.onload = (e) => {
//CALL TO A FUNCTION
}
reader.readAsDataURL(file);
}
})();
});
I want to call my old function that it works correctly but is an input file
$("#csv-file").change(handleFileSelect);
function handleFileSelect(evt) {
var file = evt.target.files[0];
Papa.parse(file, {
//rest of my code....
I want to call to handleFileSelect, actually, that function runs when the input file has changes, I want to run with my sweetAlert
how can I do?
if I just only call to handleFileSelect(); I get this error
create:335 Uncaught TypeError: Cannot read property 'target' of undefined
Update to louys answer:
my Papa.parse(file) is not working, in the console.log for file I get this
console.log(file); when all is working
File {name: "task import.csv", lastModified: 1613002044713, lastModifiedDate: Wed Feb 10 2021 20:07:24 GMT-0400 (hora de Bolivia), webkitRelativePath: "", size: 96, …}
lastModified: 1613002044713
lastModifiedDate: Wed Feb 10 2021 20:07:24 GMT-0400 (hora de Bolivia) {}
name: "task import.csv"
size: 96
type: ""
webkitRelativePath: ""
__proto__: File
console.log(file); when I use the solution
data:application/octet-stream;base64,R29vZ2xlIFBsYWNlIFVSTCxCdXNpbmVzcyBUeXBlDQpodHRwOi8vd3d3LnJlc3RhdXJhbnQuY29tLFJlc3RhdXJhbnQNCmh0dHA6Ly93d3cuaG90ZWwuY29tLEhvdGVs
If I download that file link and put a .csv extension, the file is correct, but incompatible with Papa.parse

You don't need to use a FileReader here. If there is a file... Pass it to your function.
$('#btn-file').on('click', function (){
(async () =>{
let { value: file } = await Swal.fire({
title: 'Select image',
html: 'You can download a model for your work here',
input: 'file',
showCancelButton: true,
inputAttributes: {
'accept': '.csv',
'aria-label': 'Upload your CSV file'
}
})
if (file) {
//CALL TO A FUNCTION
handleFileSelect(file); // Try passing the file result directly
})();
});
function handleFileSelect(file) {
// Remove this... The file was passed as argument
//var file = evt.target.files[0];
//rest of my code....

Related

React SPFx - Adding files to SharePoint list field using PnPjs

I'm building an application using SPFx Webpart with React. On one of my components I have a form that the user can fill out. I'm using PnPjs to push the user's responses into my list field. Everything works as expected.
I was looking at how to add a file or attachment field type to a list. I saw I can do it in the powerapps. So now in my "Product" list I have a field called attachments. When I attach files to that field from SharePoint's backend and then make a call to the list using PnPjs the attachment field does not return information about the files. But rather a boolean with a true or false.
pnp.sp.web.lists.getByTitle("Products").items.filter("Id eq '" + this.props.match.params.id + "'").top(1).get().then((items: any[]) => {
console.log(items);
}
So this works perfect and returns back the item which should have had the attachments from the code below. Now in my items console I get back Attachments: true or Attachments: false
I'm using react-dropzone to allow users to upload files. Using PnPjs how do I upload the files to that item?
Here is how I'm creating the item:
pnp.sp.web.lists.getByTitle("Requests").items.add({
Title: this.state.SuggestedVendor,
Client_x0020_Email: this.state.getEmail,
Created: this.state.startDate,
Attachments: //need help here
}
Here is my code for the dropdown files:
onDrop = (acceptedFiles) => {
console.log(acceptedFiles);
//Assuming this is where I do the logic
}
<Dropzone
onDrop={this.onDrop}
multiple
>
{({getRootProps, getInputProps, isDragActive}) => (
<div {...getRootProps()}>
<input {...getInputProps()} />
{isDragActive ? "Drop it like it's hot!" : 'Click me or drag a file to upload!'}
</div>
)}
</Dropzone>
And here is the response I get back from console.log(acceptedFiles);:
[File]
0: File {path: "John-Hancock-signature.png", name: "John-Hancock-signature.png", lastModified: 1590783703732, lastModifiedDate: Fri May 29 2020 13:21:43 GMT-0700 (Pacific Daylight Time), webkitRelativePath: "", …}
length: 1
I found this documentation here on how to push the files : https://pnp.github.io/pnpjs/sp/files/
You have to create the item, and then add an attachment to it.
You can add an attachment to a list item using the add method. This method takes either a string, Blob, or ArrayBuffer. pnp documentation
onDrop = (acceptedFiles) => {
acceptedFiles.forEach(file => {
const reader = new FileReader()
reader.onabort = () => console.log('file reading was aborted')
reader.onerror = () => console.log('file reading has failed')
reader.onload = async () => {
// get file content
const binaryStr = reader.result
// assume we have itemId
let itemId = 1;
let request = await sp.web.lists.getByTitle("Requests").items.getById(itemId)();
await request.attachmentFiles.add("file2.txt", "Here is my content");
}
reader.readAsArrayBuffer(file)
})
}

Upload image to imgur via API - Javascript

I'm trying to upload an image to imgur via their API and i'm receiving an error 400.
{"data":{"error":"Invalid URL (Array)","request":"\/3\/image","method":"POST"},"success":false,"status":400}
My code:
const submitForm = async (event, imageFile) => {
axios.post(
"https://api.imgur.com/3/image",
{ image: imageFile, type: "file" },
{
headers: {
Authorization: `Client-ID ${process.env.REACT_APP_IMGUR_CLIENT_ID}`,
},
}
);
};
When printing "imageFile":
File {
name: "1545572599598.jpg",
lastModified: 1545573667488,
lastModifiedDate: Sun Dec 23 2018 16:01:07 GMT+0200,
webkitRelativePath: "",
size: 291376, …
}
searched like everywhere on the internet.
somone have seen that before?
Thanks

HTML POST request method returns status 200 and file doesn't update

I am working on a system to upload a picture to the server.
When the file doesn't exist on the server the client receives status code 404.
When the server does have a file called in the same name as the file that the client requests to update, It receives status code 200 but the file doesn't update on the server, just no change at all.
Code:
HTML input:
<form enctype="multipart/form-data" method="post" id="pfp-upload">
<p>Please upload your new profile picture:</p>
<input type="file" class="form-control-file" id="new-pfp" accept="image/x-png,image/jpeg">
</form>
<button type="button" class="btn btn-primary" title="Popover title" data-content="" onclick="updatePfp(document.getElementById('pfp-upload') ,document.getElementById('new-pfp'))">Save changes</button>
JavaScript code running when the submit button is clicked:
async function updatePfp(form, pfp) {
var formData = new FormData(form);
let photo = pfp.files[0];
console.log(photo);
var oReq = new XMLHttpRequest();
oReq.open("POST", "/media/" + photo.name, true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
console.log("File uploaded!");
} else {
console.log("There was an error (" + oReq.status + ") while sending the file!");
}
};
oReq.send(formData);
}
Console output when the file doesn't exist on the server:
File {name: "mainmenu.png", lastModified: 1567069340052, lastModifiedDate: Thu Aug 29 2019 12:02:20 GMT+0300 (Israel Daylight Time), webkitRelativePath: "", size: 1617, …}
POST http://domainCensored/media/mainmenu.png 404 (Not Found)
There was an error (404) while sending the file!
Console output when the file exists on the server:
File {name: "mainmenu.png", lastModified: 1567069340052, lastModifiedDate: Thu Aug 29 2019 12:02:20 GMT+0300 (Israel Daylight Time), webkitRelativePath: "", size: 1617, …}
File uploaded!
After that output nothing changed on the server.
EDIT:
After some steps, I got the following:
JavaScript code:
async function updatePfp(form, pfp) {
var formData = new FormData();
let photo = pfp.files[0];
formData.append('myFile', photo);
console.log(photo);
fetch('/media/' + photo.name, {
method: 'POST',
body: formData,
}).then(response => {
return response.text();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error(error);
});
}
Console output (when the file with the same name is on the server):
File {name: "mainmenu.png", lastModified: 1567069340052, lastModifiedDate: Thu Aug 29 2019 12:02:20 GMT+0300 (Israel Daylight Time), webkitRelativePath: "", size: 1617, …}
After that line, there is another blank line, chrome says it's from this line:
console.log(data);
This still doesn't work.

Upload JSON file using Angular 6

I'm trying to load a JSON file from the user using this method:
<input
style="display: none"
type="file" (change)="onFileChanged($event)"
#fileInput>
<button (click)="fileInput.click()">Select File</button>
<button (click)="onUpload()">Upload!</button>
and this is the code in the component ts file:
export class MyFileUploadComponent {
selectedFile: File
onFileChanged(event) {
this.selectedFile = event.target.files[0];
console.log(this.selectedFile);
console.log('content: ' + JSON.stringify(this.selectedFile));
}
onUpload() {
// upload code goes here
}
}
the line console.log(this.selectedFile); does provide me with the file meta data which is:
lastModified: 1551625969247
lastModifiedDate: Sun Mar 03 2019 17:12:49 GMT+0200 (Israel Standard Time) {}
name: "manuscripts.json"
size: 6008
type: "application/json"
webkitRelativePath: ""
__proto__: File
But when I'm trying to print it's content using JSON.stringify I get: {} (empty file).
What's the cause?
Thanks.
But when I'm trying to print it's content using JSON.stringify I get: {} (empty file).
This is not a content of JSON file. It's a File object. To read content of JSON you need to use FileReader
onFileChanged(event) {
this.selectedFile = event.target.files[0];
const fileReader = new FileReader();
fileReader.readAsText(this.selectedFile, "UTF-8");
fileReader.onload = () => {
console.log(JSON.parse(fileReader.result));
}
fileReader.onerror = (error) => {
console.log(error);
}
}
JSON.Stringify does not work for File objects in TS/JS. You should extract data from File and then stringify it.
For examlple, extract file content as a string or array of strings using https://developer.mozilla.org/en-US/docs/Web/API/FileReader

ExtJs - Save selected file from filefield

I want to upload a file using the extjs6 modern toolkit. Therefor I display a MessageBox with a file chooser. How can I retrieve the selected file into a javascript object after clicking the OK button to upload it (via HTTP POST e.g.)?
this.createUploadMsgBox("File Upload", function (clickedButton) {
if (clickedButton == 'ok') {
console.log("file: " + file);
}
createUploadMsgBox: function (title, callback) {
Ext.Msg.show({
title: title,
width: 300,
buttons: Ext.MessageBox.OKCANCEL,
fn: callback,
items: [
{
xtype: 'filefield',
label: "File:",
name: 'file'
}
]
});
}
You can rum my example here:
https://fiddle.sencha.com/#view/editor&fiddle/1kro
You have two posible solutions.
One is to use a form, and send the file via form.submit() (use form.isValid() before the submit). You can retrieve the file in the server with a MultipartFile.
The other way is to use JS File API. In you createUploadMsgBox function:
this.createUploadMsgBox("File Upload", function (clickedButton) {
if (clickedButton == 'ok') {
//console.log("file: " + file);
var filefield = Ext.ComponentQuery.query('filefield')[0];
var file = filefield.el.down('input[type=file]').dom.files[0];
var reader = new FileReader();
reader.onload = (function(theFile) {
return function(e) {
console.log(e.target.result);
};
})(file);
reader.readAsBinaryString(file);
}
});
In the file object you have the basic info of the file, and then you will see in the console the content of the file.
Hope this helps!

Categories