Im having a hard time figuring out how to preview PDFs that I'm uploading using react-dropzone. PNG and JPG are working perfectly but I would also like to be able to show the user either the pdf itself or an image of the pdf.
Here's my code:
handleImageDrop = (files) => {
const currentFile = files[0]
const reader = new FileReader()
reader.addEventListener("load", () => {
this.setState({
imgSrc: reader.result
})
}, false)
reader.readAsDataURL(currentFile)
}
render() {
const { imgSrc } = this.state;
<div>
<Dropzone
onDrop={this.handleImageDrop}
multiple={false}>
{({getRootProps, getInputProps}) => {
return (
<div
{...getRootProps()}
>
<input {...getInputProps()} />
{
<p>Try dropping some files here, or click to select files to upload.</p>
}
</div>
)
}}
</Dropzone>
{ imgSrc ? <img src={imgSrc}/> : null}
</div>
</div>
)
}
}
It cannot be as simple as showing an image in a <img> tag but you could try some external library to display pdf files. Maybe have a try with react-pdf
I used PDF.js to render the PDF files. I set up a custom preview template with a canvas element and added a function in the "init" configuration that triggers when a file has been added and uses PDF.js to draw the first page of the file on the canvas.
Related
I am trying to hide my input field of a file type, however despite having the hidden attribute it will not hide itself.
However, after I remove type="file", the code will hide itself properly
May I know if anyone knows if I can hide the file with type="file"? Thank you !
The hidden and type="file" are the same attribute. If you either define attribute hidden, you cannot use file upload, or define type='file', you cannot make this element hidden. To solve the problem, you must use inline styling display: 'none' to hide this element and set the attribute type="file" without hidden.
First, declare ref for using with input element tag.
const uploadRef = useRef()
Then call the uploadRef.current.click() for show upload file window.
Code example
const FileUpload = () => {
const uploadRef = useRef(null)
const onSelectFile = e => {
const file = e.target.files[0]
if (!file) {
console.log('No file selected')
return
}
console.log(file)
console.log(file.name)
}
return (
<div>
<input ref={uploadRef} type='file' style={{display:'none'}} onChange={onSelectFile}/>
<button type='button' onClick={()=>uploadRef.current.click()}>Upload File</button>
</div>
)
}
I am cretaing a small project related to managing books using db.json file as database. This is some of the code relevant to the actual problem
index.html
<body>
<ul class="books-container"></ul>
<img src="" id="fullImage">
</body>
db.js
const container = document.querySelector('books-container')
const renderBooks = async () => {
let uri = 'http://localhost:3000/books'
const res = await fetch(uri)
const books = await res.json()
let template = '';
books.forEach(book => {
template += `
<li class="books">
<img class="image" src="${book.image}" alt="${book.title}" data-image="${book.image}" width="80px" height="115px">
<h6 class="title">${book.title}</h6>
</li>
`
})
container.innerHTML = template
}
window.addEventListener('DOMContentLoaded', () => renderBooks())
window.addEventListener('click', (e) => {
if(e.target.className == 'image') {
let imageUrl = e.target.dataset.image
document.getElementById('fullImage').setAttribute('src', imageUrl)
}
})
Here am rendering image as thumbnail and title to the html page as template. I want to display full image as modal when clicked on thumbnail so I have taken image reference and displaying full image based on click event. It's working fine and displaying the full image but when I click on that full image it disappears and gives me "undefined" value. Is there any other way to display that full image without getting undefined on click ?
Thank you
This is my folder structure
-- assets
|
- missing.jpg
and this is the function I used to render the movie div
function showMovies(movies) {
main.innerHTML = "";
movies.forEach((movie) => {
const { title, poster_path, vote_average, overview } = movie;
const movieEl = document.createElement("div");
movieEl.classList.add("movie");
movieEl.innerHTML = `
<img
src="${IMG_PATH + poster_path}"
alt="${title}"
/>
<div class="movie-info">
<h3>${title}</h3>
<span class="${getClassByRate(vote_average)}">${vote_average}</span>
</div>
<div class="overview">
<h3>Overview</h3>
${overview}
</div>
`;
main.appendChild(movieEl);
});
}
I am trying to change the alt image in this function to display an image in my assets folder instead of just the text title.
If I understand you correctly you want to add an image when there is no image found right?
ok, so there are multiple approaches to this problem, first, if you have an invalid path, use the terniary operator to src your image correctly
src=`${IMG_PATH ? IMG_PATH + poster_path : '/assets/missing.jpg'}`
But... if the image fails to load because of the server being unavailable or some 400/500 error then that's a different story, My personal approach is to make a div with the size of the image and set multiple backgrounds using css properties for instance....
background: url("/path_to_movie_poster.gif"), url("/assets/missing.jpg");
This way if the first source failed for some reason then the default image will kick in.
Make sure your default image is the last in the least otherwise it will be on top.
I'm looking to display the contents of a .txt file stored in dropbox via the dropbox API.
I'm already pulling through and displaying images by creating src url blobs
All of the examples I've found through researching either use jQuery or ajax. Since I'm already accessing these files through the API surely there isn't a need for another call up to the dropbox server?
I've tried to use the embed tag but the browser then tries to download the file.
How do you display a txt file's content in react using the Dropbox API?
class Project extends React.Component{
constructor(){
super();
this.state = {
fileSource: [],
}
}
componentDidMount(){
var that = this;
var sources = [];
var link = "/"+this.props.title;
dbx.filesListFolder({path: link})
.then(function(response) {
...
...
//call to dropbox
...
...
var newUrls=window.URL.createObjectURL(response.fileBlob);
sources.push(newUrls);
})
.then(function(){
that.setState({
fileSource: sources,
});
});
}
});
}
render() {
if(!this.state.fileSource.length)
return null;
let text = this.state.fileSource.map((el, i) =>
<embed src={el}/>
)
return (
<div className="projectWrapper">
{text}
</div>
);
}
}
Update: I came across this previous question which creates a fileBlob from the object and then uses FileReader() and readAsText() to display the contents.
It is possible to add a image into quill JS editor from a url but can't find a way to add an image from computer like all the traditional rich text editors do.
Is there any way that serves this purpose?
You can do the following:
quill.getModule("toolbar").addHandler("image", () => {
this.selectLocalImage();
});
function selectLocalImage() {
var input = document.createElement("input");
input.setAttribute("type", "file");
input.click();
// Listen upload local image and save to server
input.onchange = () => {
const file = input.files[0];
// file type is only image.
if (/^image\//.test(file.type)) {
this.saveToServer(file, "image");
} else {
console.warn("Only images can be uploaded here.");
}
};
}
function saveToServer(file) {
// Upload file to server and get the uploaded file url in response then call insertToEditor(url) after getting the url from server
}
function insertToEditor(url) {
// push image url to editor.
const range = quill.getSelection();
quill.insertEmbed(range.index, "image", url);
}
This is simple. Simply add a button with a class of ql-image.
Example below:
<div id="toolbar" class="toolbar">
<span class="ql-formats">
<button class="ql-image"></button>
</span>
</div>
Finally, instantiate Quill with the toolbar container set to your toolbar element:
var quill = new Quill('#editor', {
modules: {
toolbar: {
container: '#toolbar'
}
},
theme: 'snow'
});
This will add the image to the content editable area you have as a base 64 encoded string on an img element.