Javascript: Upload File

How to get file name from the uploaded file using javascript?

File inputs have a files property that can be interrogated to obtain the file name, MIME type, and size (in bytes).

Each item in the files list is a File, which is an object (not a string) that has a .name property.

For more info, see Getting information on selected files from MDN.

In React, you can get this information from the event argument that is provided to the onChange handler. I think that's generally better than using a ref, because it mirrors the pattern you'd use with other kinds of inputs.


I think the reason your code is failing is because you're not managing your data well.

I think you want something like this:

let [ filename, setFilename ] = React.useState<string>('')

function onChangeFile( event: React.ChangeEvent<HTMLInputElement> ): boolean {
if(event.files && event.files.length) {
setFilename(event.files[0].name)
}
return true
}

<FormField
label="file"
fieldId={`${fieldRoot}.kubeConfig`}
>
{({form}: FieldProps) => (
<>
<input
type="text"
value={filename}
/>
<input
type="file"
style={{display: 'none'}}
accept=".pem"
ref={inputRef}
onChange={onChangeFile}
/>
<button onClick={handleUploadClick}> Upload </button>
</>
)}
</FormField>

A few things to note:

  • we don't need two functions for this (one to store and one to retrieve), we only need one change handler
  • we use regular React state to hold onto the filename, instead of whatever you're doing with lodash get
  • this does not use the form.setFieldValue; I don't see the implementation of <FormField> here, so there's no way for us to know how to use it properly
  • I don't see the implementation of handleUploadClick, so I'm assuming that all it does is fire a click event on the hidden file input (which is pretty common)

Also, you should never define DOM event handlers as async. DOM event handlers do not understand Promises. A DOM event handler must return a boolean, not a boolean inside a Promise, if you want the page to react properly.

Is it Possible to make a button as File upload Button?

You can keep a <input type='file' hidden/> in your code and click it using javascript when the user clicks on the "Upload MB" button.

Check out this fiddle.

Here is the snippet.

document.getElementById('buttonid').addEventListener('click', openDialog);
function openDialog() { document.getElementById('fileid').click();}
<input id='fileid' type='file' hidden/><input id='buttonid' type='button' value='Upload MB' />

Javascript: Uploading a file... without a file

Why not just use XMLHttpRequest() with POST?

function beginQuoteFileUnquoteUpload(data)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
alert("File uploaded!");
}
xhr.send("filedata="+encodeURIComponent(data));
}

The handler script at the server just writes the file data to a file.

EDIT
File upload is still a http post with a different content type. You can use this content type and separate your content with boundaries:

function beginQuoteFileUnquoteUpload(data)
{
// Define a boundary, I stole this from IE but you can use any string AFAIK
var boundary = "---------------------------7da24f2e50046";
var xhr = new XMLHttpRequest();
var body = '--' + boundary + '\r\n'
// Parameter name is "file" and local filename is "temp.txt"
+ 'Content-Disposition: form-data; name="file";'
+ 'filename="temp.txt"\r\n'
// Add the file's mime-type
+ 'Content-type: plain/text\r\n\r\n'
+ data + '\r\n'
+ boundary + '--';

xhr.open("POST", "http://www.mysite.com/myuploadhandler.php", true);
xhr.setRequestHeader(
"Content-type", "multipart/form-data; boundary="+boundary

);
xhr.onreadystatechange = function ()
{
if (xhr.readyState == 4 && xhr.status == 200)
alert("File uploaded!");
}
xhr.send(body);
}

If you want to send additional data, you just separate each section with a boundary and describe the content-disposition and content-type headers for each section. Each header is separated by a newline and the body is separated from the headers by an additional newline. Naturally, uploading binary data in this fashion would be slightly more difficult :-)

Further edit: forgot to mention, make sure whatever boundary string isn't in the text "file" that you're sending, otherwise it will be treated as a boundary.



Related Topics



Leave a reply



Submit