How do I download files from my gridFS store in Mongodb?
I have the following code:
#bottle.route('/download')
def download():
file_id = ObjectId(bottle.request.query.id)
if file_id:
try:
file_to_download = fs.get(file_id)
except:
return "document id not found for id:" + file_id, sys.exc_info()[0]
return (file_to_download)
return bottle.template('files_test/download')
which returns gibberish in the browser. How do I specify that I want it to be downloaded?
Edit:
This is the hyperlink I want to use to download the file:
<--Download File-->
Have I missed it here well?
See this question:
flask return image created from database
You need to set the Content-Type and Content-Disposition headers so the browser knows what type of file you're sending, and that it should be downloaded rather than displayed.
Related
I am importing a Smartsheet Report through Python, using an API. One of the columns in this report contains a hyperlink that works in Smartsheet, however when importing the report with Python I only receive the words of this column, and not the link behind them. Is it possible to get the URLs of the sheets that these hyperlinks are referring to in any other way? I was thinking maybe based on SheetID (which I can find using the title of the indepentent sheets), but all other suggestions are very welcome!
I've been unable to reproduce the problem you've described.
The report I'm testing with contains the following data. The Google link in the first row is a normal URL that points to https://www.google.com and the Contacts List link in the second row is a sheet hyperlink that points to another sheet in Smartsheet.
First, I use the Python SDK to get the report and then print out the contents of the second cell of the first row (i.e., the one that contains the Google hyperlink):
reportID = 6667768033503108
report = smartsheet_client.Reports.get_report(reportID)
print(report.rows[0].cells[1])
The result of this code showed the following output (JSON formatted here for readability):
{
"columnId": 5228827298293636,
"displayValue": "Google",
"hyperlink": {
"url": "https://www.google.com"
},
"value": "Google",
"virtualColumnId": 2581703205119876
}
So, accessing the URL of the hyperlink can be accomplished with the following code:
url = report.rows[0].cells[1].hyperlink.url
print(url) #shows output: https://www.google.com
The same approach works for getting the URL of the sheet hyperlink in the second row. i.e., running the following code:
reportID = 6667768033503108
report = smartsheet_client.Reports.get_report(reportID)
url = report.rows[1].cells[1].hyperlink.url
print(url) #shows output: https://app.smartsheet.com/sheets/[ID]
This approach should work for you, but if for some reason you're seeing that the cell object in the JSON response (when using the Python SDK) for the cell that contains the link doesn't actually contain a hyperlink object with a url property -- that might indicate a bug either with the Python SDK or with the underlying API. In that case, you might try getting the URL string by using a dictionary, as shown in the following code. (Note: you'll need to import json for this code to work).
reportID = 6667768033503108
# get the report
report = smartsheet_client.Reports.get_report(reportID)
# load the contents of the second cell in the first row
resp_dict = json.loads(str(report.rows[0].cells[1]))
# read the url property from the dictionary
url = resp_dict['hyperlink']['url']
print(url) #shows output: https://www.google.com
I build a flutter web app and My requirement is to get a file(PDF) and write it in file or download it,
i get my file from an API and it gave me a file not a link,
Can anyone help me with this. An example would be more helpful.
Thank you
Use this utility method:
import 'dart:html' as html;
void openDownloadLink(String href, String filename) {
html.document.createElement('a') as html.AnchorElement
..href = href
..download = filename
..dispatchEvent(html.Event.eventType('MouseEvent', 'click'));
}
Uri getHref() => Uri.parse(html.window.location.href);
The first parameter is the URL of the file to be downloaded, the second is the 'suggested' filename that the browser will show. Note that you can't put in a full path to the local file - the file name is just a suggestion.
The getHref function may be useful. It returns a Uri representing where the Flutter web app was launched from. If you want a path relative to that for your PDF, modify it, keeping the https://server... part the same. Equally, you could probably use a relative path as the href parameter, like ../pdfs/somefile
I am trying to get uploaded file's content (using POST) WITHOUT having to create/copy this file to the local directory. Is there any way it's possible in scala?
Here's my code:
def uploadSchema = Action(parse.multipartFormData) { request =>
request.body.file("source").map { sourceFile =>
val filename = Paths.get(sourceFile.filename).getFileName
sourceFile.ref.moveTo(Paths.get(s"/usr/local/polymer/schema/uploads/$filename"), replace = true)
Ok(s"Uploaded successfully!"+sourceFile.)
}.getOrElse {
Redirect(routes.NLPController.uploadSchema).flashing("error" -> "Missing file.")
}
What I want to do is, instead of doing
sourceFile.ref.moveTo(Paths.get(s"/usr/local/polymer/schema/uploads/$filename"), replace = true)
Do something like
val content : String = Source.fromFile(file).getLines.mkString
Here's my API from routes file
POST /api/upload controllers.NLPController.uploadSchema
Is it possible to this? If not, why?
You are saying that you want to do the following:
You want to upload something through your Play app to a machine.
You don't want to copy it to the machine's local directory.
The problem here is, where the file should go then? If I have an app in server, and I upload my file, with this method, the file will be always be on the server first. Because it should be copied somewhere before then you want to move it somewhere else (cloud, another backup server).
What about reading the files content?
This is another question, does not related to upload, rather than reading the files content, you can do this:
import scala.io.Source
val myFileContent = Source.fromFile("myFile.txt").getLines.mkString
Update Note
Ok, you are saying, in comments, that you have app A that you want to get the content of the file and then send it to the app B. Well why don't you do this:
Route with Query String: Have a route that gets the file's path as a query string:
GET /file-content controllers.file.readContent (path: String)
Then you call the app like this:
/file-content?path=whereever/i-want/myfile-be.txt
Method to read the content and put it in a response: Then within your readContent method you return the body of the file, to whomever who calls the app A:
def readContent (filePath: String) = Action{
implicit request =>
Ok(Source.fromFile(filePath).getLines.mkString))
}
Update Note 2: Don't forget about security!
The above solution works fine to read the data, and give it back. But, you should also take of security as well. You don't want to give the content of the file to anyone who calls that url. You could add token within the caller app, so the app who deals with the content of the data, first check if the user is authorized, and then check for the content of the file.
I'm building an application that inserts documents into MarkLogic server using the MLPHP library. The problem is when I insert a binary document, for example a PDF. The mime type will not be set properly, therefore the file cannot be opened as it should.
This is the code I use to insert a document:
// initialize REST client
$client = new MLPHP\RESTClient('127.0.0.1', 8010, 'v1', '', 'rest-writer-user', 'writer-pw');
// create new document and load content
$doc = new MLPHP\Document($client);
$doc->setContentType("application/pdf");
$doc->setContentFile("demo.pdf");
$doc->write('pdf_demo');
This is a dump of the $doc object after submitting to the server:
And here we have the inserted document in the search results:
But as expected, the browser cannot handle the file due to the wrong mimetype:
Anyone has got a clue what's going wrong here?
Check to see what the Response Header for content type is.
You Might have to set the format URL Parameter to binary. You can read the full documentation at http://docs.marklogic.com/REST/GET/v1/documents
here is what the request would look like
http://localhost:8010/v1/documents?uri=/pdf_demo.pdf&format=binary
I'm testing out the new API, but having no luck downloading a test image file. The file exists, is accessible through the web UI, and is retrievable using the v1.0 API.
I'm able to access the metadata ("https://api.box.com/2.0/files/{fileid}") using both commandline curl and pycurl. However, calls to "https://api.box.com/2.0/files/{fileid}/data" bring back nothing. An earlier post (5/1) received the answer that the download feature had a bug and that "https://www.box.com" should be used as the base URL in the interim. That, however, just provokes a 404.
Please advise.
You should be able to download via http://api.box.com/2.0/files/<fildID>/content ... Looks like we have a bug somewhere in the backend. Hope to have it fixed soon.
Update 11/13/2012 -- This got fixed at least a month ago. Just updated the URL to our newer format
For me it works when its /content instead of /data... python code below
import requests
fileid = str(get_file_id(filenumber))
url = https://api.box.com/2.0/files/1790744170/content
r = requests.get(url=url, headers=<HEADERS>, proxies=<PROXIES>)
infoprint("Downloading...")
filerecieved = r.content
filename = uni_get_id(fileid, "name", "file")
f = open(filename, 'w+')
infoprint("Writing...")
f.write(filerecieved)
f.close()