## This backend code to upload files both image and PDF file Flask==1.1.2 Flask-PyMong0==2.3.0 ##
def file_upload():
try:
_json = request.form
_title = _json['title']
_desc = _json['desc']
if 'file' in request.files:
_file = request.files['file']
_filename = _file.filename
_file_mimetype = _file.content_type
mongo.save_file(_filename, request.files['file'])
user = mongo.db.userReg.find_one({'email': session['user']})
mongo.db.upload.insert_one(
{'title': _title, 'desc': _desc, 'filename': _filename,
'file_mimetype': _file_mimetype, 'user': {'userId': user['_id']}, 'date': datetime.datetime.now()})
mongo.db.upload.find({}).sort('date', -1).limit(1)
message = {
'data': "null",
'result': {'isError': 'false', 'message': 'File added', 'status': 200, }
}
return jsonify(message)
except Exception as e:
return internal_error()
This is viewFile function to get the file response and try to view the file but not showing the image
import { Document, Page, pdfjs } from 'react-pdf';
const API = process.env.REACT_APP_API;
pdfjs.GlobalWorkerOptions.workerSrc =`//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js`;
const viewFile = async (filename) => {
try {
const result = await axios.get(`${API}/file/${filename}`, {
responseType: 'blob'
});
const fileURL = URL.createObjectURL(result.data)
setFileURL(fileURL);
setErrorMsg('');
} catch (error) {
if (error.response && error.response.status === 400) {
setErrorMsg('Error while Viewing file. Try again later');
}
}
};
function onDocumentLoadSuccess({ numPages }) {
setNumPages(numPages);
setPageNumber(1);
}
function changePage(offset) {
setPageNumber(prevPageNumber => prevPageNumber + offset);
}
function previousPage() {
changePage(-1);
}
function nextPage() {
changePage(1);
}
<div className="files-container">
{errorMsg && <p className="errorMsg">{errorMsg}</p>}
{
(fileExtension === 'pdf') ? (
<Fragment>
<Document
file={fileURL}
onLoadSuccess={onDocumentLoadSuccess}
>
<Page pageNumber={pageNumber} />
</Document>
<div>
<p>
Page {pageNumber || (numPages ? 1 : "--")} of {numPages || "--"}
</p>
<button
type="button"
disabled={pageNumber <= 1}
onClick={previousPage}>
Previous
</button>
<button
type="button"
disabled={pageNumber >= numPages}
onClick={nextPage}
>
Next
</button>
</div>
</Fragment>
) : (
<Fragment>
<img src={fileURL} alt={match.params.filename} className="view-file"/>
</Fragment>
)
}
</div>
"react": "^17.0.1", "react-pdf": "^5.1.0". Previously in 2021, I ran the code successfully and showed the both PDF and image file but now this code is not working###
In case of viewing image file, I got only "alt-text" output in view page that not showing any error in console.
In case of viewing PDF file, I got the output "Failed to load PDF file" in view page that showing error in console. "InvalidPDFException"