Display a picture saved in HTML into a Vue.js page - javascript

I am currently trying to display a local picture saved in HTML into my Vue.js page.
I have tried to load the content of the HTML file into a variable using the following lines:
computed: {
compiledHtml: function() {
return this.asset;
}
const path = 'http://localhost:5000/load_results'
axios
.get(path)
.then((res) => {
this.asset = res.data
})
Then I have tried to display it using v-html:
<div v-html="compiledHtml"></div>
It actually works with a simple HTML file which contains a few lines, for example:
<h1> test load HTML file </h1>
However, my picture size is 3.5Mb and is much more complex than the example I gave you and when I try to display it, it gives me a blank space.
Is there anyone who knows how to overcome this problem? Thanks.
Here is the GET method I have used:
#bp.route('/load_results', methods=['GET'])
def load():
f = codecs.open("./file.html", 'r', 'utf-8')
return f.read()

I have successfully overcome this problem by modifying my GET method to open the file inside my API like this :
import webbrowser
#bp.route('/load_html_picture_file', methods=['GET'])
def load():
webbrowser.open(path_to_file)
Therefore it open my image in a new tab in my webbrowser.
Thanks anyway.

Related

Laravel, sending PDF from controller to JS variable

I'm trying to make a very barebones page that loads in two specific PDF documents and on page load would simply display one and then after a 60 second timelapse, would cycle over and show the other.
My issue, currently, is simply getting the PDFs into variables in the JS so that I can assign the time cycle to them.
How can I take the PDFs being sent from the controller and put them into JS variables in order to accomplish this properly?
public function getPDFDocs()
{
if(Storage::disk('test_docs')->exists('testFirstFile.pdf')){
$file1 = Storage::disk('test_docs')->get('testFirstFile.pdf');
}
if(Storage::disk('test_docs')->exists('testSecondFile.pdf')){
$file2 = Storage::disk('test_docs')->get('testSecondFile.pdf');
}
return view('test.index')
->with('firstFile', $file1)
->with('secondFile', $file2);
}
index.blade.php
#section('loadjs')
getPDFPages() {
let visible = [];
//visible.push ({pages here??})
}
#endsection
First of all, it seems you are getting the contents of file PDF, not their path. So it may not be efficient to transfer entire PDF data in your initial HTTP response.
Do this PDF files publicly accessible? If so; return their http url instead of pdfs' data.
After that; to inject a data from Laravel backend to JavaScript in a blade file; best approach is turn your data to json, send it to blade and write it as an HTML element's data- attribute, then in JavaScript read it from data- attribute and decode json to a JS object.
Here is an example;
public function getPDFDocs()
{
if(Storage::disk('test_docs')->exists('testFirstFile.pdf')){
// assuming this files publicly accessible and use url method
$files[1] = Storage::disk('test_docs')->url('testFirstFile.pdf');
}
if(Storage::disk('test_docs')->exists('testSecondFile.pdf')){
// assuming this files publicly accessible and use url method
$files[2] = Storage::disk('test_docs')->url('testSecondFile.pdf');
}
return view('test.index', ['files' => $files]);
}
In your blade;
<!-- write down your html here -->
<span id="filesdata" data-files="{{ json_encode($files) }}" ></span>
#section('loadjs')
var filesJson = document.getElementById('filesdata').getAttribute('data-files');
var files = JSON.parse(filesJson);
// now you have your files, lets check them
console.log(files);
getPDFPages() {
let visible = [];
//visible.push ({pages here??})
}
#endsection
And use PDF URLs to show them in client. Let the client request and get raw pdf data, don't try to return them in your initial response.

How to fetch the result of the cherrypy function?

I have the website hosted on local using XAMPP and the server written using cherrpy. I want to use cherrpy to return data and update the paragraph in the HTML page. Here's my code:
index.html
<p id="curtains_status" style="color: white;">a </p>
<script>
curtains_submit.onclick = function() {
response = await fetch("//127.0.0.1:8080/test");
alert(await response.text);
};
</script>
I created the paragraph to display its current state. I attached some code to it to (hopefully) fetch the data from the server.
server.py
import cherrypy
class Site(object):
#cherrypy.expose
def test(self):
return "test"
cherrypy.quickstart(Site())
Here I defined the test function to return the 'test' so that I can alert it in index.html The problem is I don't get the alert executed.
Does anybody know what's the issue?

How to send file with react and django rest

How can I send an image file from react to django.
I am new to react and django , currently I am being successful in sending and getting data from/to the endpoints, now I want to send an image file or any other file from react to django or get image file from django to react.I wrote some code but its not working properly and i am facing quite difficulty to send file, I researched but not get any useful link.Kindly can someone share link from where I can get better understanding how it works.Here below is my try:
REACT PART
let doc=new JsPDF();
doc.addImage(img,'JPEG',30,30);
//doc.save('test.pdf');
let formdata=new FormData();
formdata.append('file',doc);
fetch(`http://127.0.0.1:8000/chauffeur/pdf_upload/`,
{
method: 'POST',
body:formdata,
}
).then(response => response.json()).catch(error => console.error('Error:', error));
DJANGO PART
class PdfUpload(APIView):
parser_classes = (MultiPartParser, FormParser,)
def get(self, request):
return Response([PdfSerializer(file).data for file in Pdf.objects.all()])
def post(self,request):
payload=(request.data,request.FILES)
print("Hello")
print(payload)
serializer=PdfSerializer(data=payload)
if serializer.is_valid():
serializer.save()
return Response("File Saved in Backend",status=status.HTTP_201_CREATED)
return Response(serializer.errors,status=status.HTTP_400_BAD_REQUEST)
But I am getting too many errors from above code, like no file submitted or expected dict but receive list, can someone fix above code or can share helpful links from where I can understand better.Thanks in advance!
If the name of object in your models.py is for example PdfModel write like this:
from django.core.files import File
def post(self, request):
my_file = File(request.data.get('file'))
new_pdf_file = PdfModel.objects.create(
field1=request.data.get('field1'),
field2=request.data.get('field2'),
field3=my_file )
new_pdf_file.save()
return Response({"something","something")

How to scrape AJAX based websites by using Scrapy and Splash?

I want to make a general scraper which can crawl and scrape all data from any type of website including AJAX websites. I have extensively searched the internet but could not find any proper link which can explain me how Scrapy and Splash together can scrape AJAX websites(which includes pagination,form data and clicking on button before page is displayed). Every link I have referred tells me that Javascript websites can be rendered using Splash but there's no good tutorial/explanation about using Splash to render JS websites. Please don't give me solutions related to using browsers(I want to do everything programmatically,headless browser suggestions are welcome..but I want to use Splash).
class FlipSpider(CrawlSpider):
name = "flip"
allowed_domains = ["www.amazon.com"]
start_urls = ['https://www.amazon.com/s/ref=nb_sb_noss?url=search-alias%3Daps&field-keywords=mobile']
rules = (Rule(LinkExtractor(), callback='lol', follow=True),
def parse_start_url(self,response):
yield scrapy.Request(response.url,
self.lol,
meta={'splash':{'endpoint':'render.html','args':{'wait': 5,'iframes':1,}}})
def lol(self, response):
"""
Some code
"""
The problem with Splash and pagination is following:
I wasn't able to product a Lua script that delivers a new webpage (after click on pagination link) that is in format of response. and not pure HTML.
So, my solution is following - to click the link and extract that new generated url and direct a crawler to this new url.
So, I on the page that has pagination link I execute
yield SplashRequest(url=response.url, callback=self.get_url, endpoint="execute", args={'lua_source': script})
with following Lua script
def parse_categories(self, response):
script = """
function main(splash)
assert(splash:go(splash.args.url))
splash:wait(1)
splash:runjs('document.querySelectorAll(".next-page")[0].click()')
splash:wait(1)
return splash:url()
end
"""
and the get_url function
def get_url(self,response):
yield SplashRequest(url=response.body_as_unicode(), callback=self.parse_categories)
This way I was able to loop my queries.
Same way if you don't expect new URL your Lua script can just produce pure html that you have to work our with regex (that is bad) - but this is the best I was able to do.
You can emulate behaviors, like a ckick, or scroll, by writting a JavaScript function and by telling Splash to execute that script when it renders your page.
A little exemple:
You define a JavaScript function that selects an element in the page and then clicks on it:
(source: splash doc)
# Get button element dimensions with javascript and perform mouse click.
_script = """
function main(splash)
assert(splash:go(splash.args.url))
local get_dimensions = splash:jsfunc([[
function () {
var rect = document.getElementById('button').getClientRects()[0];
return {"x": rect.left, "y": rect.top}
}
]])
splash:set_viewport_full()
splash:wait(0.1)
local dimensions = get_dimensions()
splash:mouse_click(dimensions.x, dimensions.y)
-- Wait split second to allow event to propagate.
splash:wait(0.1)
return splash:html()
end
"""
Then, when you request, you modify the endpoint and set it to "execute", and you add "lua_script": _script to the args.
Exemple :
def parse(self, response):
yield SplashRequest(response.url, self.parse_elem,
endpoint="execute",
args={"lua_source": _script})
You will find all the informations about splash scripting here
I just answered a similar question here: scraping ajax based pagination. My solution is to get the current and last pages and then replace the page variable in the request URL.
Also - the other thing you can do is look on the network tab in the browser dev tools and see if you can identify any API that is called. If you look at the requests under XHR you can see those that return json.
You can then call the API directly and parse the json/ html response. Here is the link from the scrapy docs:The Network-tool

One main JS varibles file for multiple HTML files

So I am wanting to create one file where I can list and edit links without opening every file.
So I am wanting to have a page like http://example.com/links.js and in there I want to have all my information where I can information.
I will have around 20 http://example.com/link1.html etc. So instead of opening every HTML file to edit it, I would like to have just one main file where I can set for example links and titles.
I am not perfect at JS but I do understand the most parts. So in the jar file I will have like "var link1 = www.google.com" and inside link1.html, it will turn out as <a href="www.google.com></a> Something like that.
Sorry if you do not understand this as I am tired and cannot explain correctly. Thanks.
I managed to find a way to do this by using :)
link3 = function() {
location.href = "http://google.com";
}
Though it is a broad topic but hopefully this will help you in designing your application.
You can have one js file will a json object. Example
links.js
var Links = {}; // namespacing
Links.linkObject = {
linkOne:"someLink",
linkTwo:"someLinkTwo",
//Rest of links
}
Links.linkContains() {
return Links.linkObject;
}
Import this file using script tag
<script src="links.js"></script>
Now in your main js file or any other file you can call this inside some function
function customFunction() {
var getLinks = Links.linkContains() // will return the json array of links
}
Once you get the getLinks you can use dot or bracket notation to get the value.
For example getLinks.linkOne will return someLink.
You can use this object to retrieve value anywhere in your application and when you will change the relevant value in link.js it will reflect everywhere

Categories

Resources