Getting the size of an uploaded file React JS - javascript

How would I go about finding the size of an uploaded file in React JS?

Let's say, your jsx is like <input type="file" onChange={this.fileChangedHandler}/>
Now, in your fileChangedHandler, you'll have to do something like below:
fileChangedHandler = (event) => {
let file_size = event.target.files[0].size;
//or if you like to have name and type
let file_name = event.target.files[0].name;
let file_type = event.target.files[0].type;
//do whatever operation you want to do here
};

You will first need to grab the input type file upload like
var uploadDocuments = document.getElementById('file-0'); //grab html file-upload element
and can get the file size using .size attribute.
uploadDocuments.files[0].size //this gives the size of uploaded file

React.js is just used for your view. You can use normal javascript for everything else.
If you wanted to find a file's size at some url with jquery:
var req = $.ajax({
type: "HEAD",
url: 'some/url/here',
success: function () {
console.log(req.getResponseHeader("Content-Length")); //Filesize
}
});
In the success callback you could save the size into React's state using setState(), then display the size in a div within your render method.
You are also not limited to using jquery for the HEAD request. SuperAgent is another popular one.

Related

How to get the File Type of a File in Sharepoint

I'm trying to load in documents from the Documents library in SharePoint and I want to be able to filter them by file type (Word Doc, Excel Sheet, etc.) from my application. I've figured out how to get the icon for the file type using mapToIcon, but I can't seem to find anywhere how to get the file type.
Is there any function or API call to get the file type of a file? I would prefer to not have to hard code each type based on file extension but I may need to do that.
Here is a bit of my code for reference
// data returned from an ajax call to get all documents
var results = data.d.results;
for(var i = 0; i < results.length; i++){
// get the name of the document
var name = results[i].Name;
// retrieve the icon for the file type through an ajax call
var icon;
$.ajax({
url: siteUrl + "/_api/web/maptoicon(filename='" + name + "',progid='',size=0)"
/*headers*/,
success: function(data){
// get the icon
icon = data.d.MapToIcon;
},
});
}
File_x0020_Type property of SP.ListItem resource could be utilized for that purpose.
In case if your query (seems to be your scenario) returns files SP.FileCollection resource, file type could be retrieved like this:
/_api/web/getfolderbyserverrelativeurl('<folder url>')/Files?$select=ListItemAllFields/File_x0020_Type&$expand=ListItemAllFields
In case if your query returns list items SP.ListItemCollection resource, file type could be retrieved like this:
/_api/web/lists/getbytitle('<list title>')/items?$select=File_x0020_Type

Does fetch support multiple file upload natively?

Summary
I am trying to set my FormData properly using javascript.
I need to be able to upload jpg/png, but I might need to upload some other file types pdf/csv in the future using fetch.
Expected
I expect it to append the data to the form
Error
Working
This snippet is working fine:
const formData = new FormData(document.querySelector('form'));
formData.append("extraField", "This is some extra data, testing");
return fetch('http://localhost:8080/api/upload/multi', {
method: 'POST',
body: formData,
});
Not working
const formData = new FormData();
const input = document.querySelector('input[type="file"]');
formData.append('files', input.files);
Question
Does fetch support multiple file upload natively?
If you want multiples file, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('http://localhost:8080/api/upload/multi', {
method: 'POST',
body: data
})
The issue with your code is in the lineformData.append('files', input.files);
Instead of that, you should upload each file running a loop with unique keys, like this
const fileList = document.querySelector('input[type="file"]').files;
for(var i=0;i<fileList.length;i++) {
formData.append('file'+i, fileList.item(i));
}
I have created a simple error fiddle here with your code. You can check its' submitted post data here, where you can see that no file has been uploaded.
At the bottom of the page you can find
.
I have corrected the fiddle here with the fix. You can check its'post data from the server, where it shows the details of the two files that I uploaded.
I mentioned this on a similar question: I had the same problem, but with a PHP backend. The unique formData keys work, but I found that the classic HTML notation worked just fine and simply results in an array on the server.
formData.append('file[]', data[i]);
I like that a lot better, since I can use the same methods to process this as with a classic <input type="file" multiple />.

How to set a specific json response object as a js var - Cloudinary

I am using Cloudinary to host my profile images that are set by users.
I'm mostly using PHP for my web application -> Here are the instructions as provided by Cloudinary http://cloudinary.com/documentation/php_image_upload#overview
The problem that I encounter is that I want to display the image directly after upload by parsing the newly created URL for the image that is returned by JSON.
When I do the console.log as provided by Cloudinary:
$(document).ready(function() {
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
console.log(data);
return true;
});
});
This is the console.log response that I receive
Can anyone please help me with a javascript or JQuery function that I can use in order to display the updated image with in my image tag.
You need read the tree...
jqXHR.responseJSON.url
In this case, use
data.result.url
See example of http://cloudinary.com/documentation/php_image_upload#preview_thumbnail_progress_indication_multiple_images
Can you update the src of your image tag based on the json returned?
Something like this in the callback function:
var imgDiv = document.getElementById("profile");
imgDiv.src = data.jqXHR.responseJSON.url;

Store file content in a table(html table tr td) jquery

I wanted to insert multiple files in database by uploading/adding the each file content to a table then after adding all files to the table i add the tables' value including the file content in a form data which i pass to ajax. I tried
var file = $('#file')[0].files[0];
//var file = document.getElementById('file').files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var blob = new Blob([file], {
type: "application/octet-binary"
});
var filecontent = blob;
Here i used the value of filecontent to be passed to ajax but in php the condition if(!empty($_FILES) remaind false)
and on console.log filecontent looks like [object Blob] i want to do to achieve my primary goal which is to store to database i already asked a question about it. I can be found here this is the problem why i asked the first one.
My question is How to store file content to a variable in this case store the value of $('#file')[0].files[0] to file.
UPDATE
When i used the value of var file = $('#file')[0].files[0]; i still get the same error
UPDATE
Is it possible to store the input:file into table td or input or any other element and reuse that file if needed
To store content of a file into a variable you first need to read them , so you will have to use a FileReader.
For example readAsText() method Syntax:
instanceOfFileReader.readAsText(blob[, encoding]);
The readAsText method is used to read the contents of the specified
Blob or File. When the read operation is complete, the readyState is
changed to DONE, the loadend is triggered, and the result attribute
contains the contents of the file as a text string.
Hence you can store the result to your variable.

how to export csv file with filename

I want to export the exist data into csv file. I try to use this code:
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();
it works but I can design filename. I can only get the dialog with name like "MVeAnkW8.csv.part" which I don't know where the name come from.
How can I assign filename in the first dialog? Thanks in advance.
update:
I am now using rails. Actually I have a method in server side names export_to_csv. In end of this method, I use code like that:
send_data(csv_string,
:type => 'text/csv; charset=utf-8;',
:filename => "myfile.csv")
It works and I can specify the file name.
For now, I want to use ajax to get more csv files(that is the reason why I want to use javascript, because a normal http request can only get one file to be downloaded).
I use js code like that:
$.post("export_to_csv",
function(data) {
var uriContent = "data:text/csv;charset=utf-8," + encodeURIComponent(data);
var myWindow = window.open(uriContent);
myWindow.focus();});
It get the data from server side and I try to transfer it into csv. I can get a file but can't specify the file name.
As I know, you can specify the filename only in chrome 14+.
Take a look at this question: Is there any way to specify a suggested filename when using data: URI?
Update!
If you want to download multiple csv files "at once", you can zip them together, or save each file on the server separately (each file now has a url that points to it - if you place them inside the 'www' folder).
Then send the file names and their path/url to the client via ajax (use a json encoded list for example).
In the ajax callback function: take the list of the files and open each file-url in a separate popup.

Categories

Resources