I need download a file from a directory in Symfony. The problem is, I need download this file when I am authenticated.
For that, I create a endpoint (GET method) with an ID (the id file), and I am doing the call from a React app passing in the Headers an authorization bearer.
The problem is, the file is not download directly, but if I enter in DevTools from Chrome, I see that in the response exists the file, but it is not downloaded.
This is the PHP code:
$file = new File($fullPath);
return $this->file($file);
How could I download the file?
This is an example code of mine:
/**
* #param Product $product
* #param TranslatorInterface $translator
*
* #SWG\Response(
* response=200,
* description="Get allergensheet of a product",
* )
* #SWG\Tag(name="Product")
*
* #Route("/allergensheet/{id}", methods="GET")
*
* #Security(name="Bearer")
* #return Mixed
*/
public function downloadAllergenSheet(Product $product, TranslatorInterface $translator) {
$allergens = $product->getAllergens();
if($allergens instanceof Allergens) {
if($allergens->getHasSheet()) {
$fs = new Filesystem();
if($fs->exists($translator->trans($product->getArticleNr() . '_allergensheet'))) {
return new BinaryFileResponse($translator->trans($product->getArticleNr() . '_allergensheet'));
}
else {
return new JsonResponse(false, Response::HTTP_NO_CONTENT);
}
}
else {
return new JsonResponse(false, Response::HTTP_NO_CONTENT);
}
}
else {
return new JsonResponse(false, Response::HTTP_NO_CONTENT);
}
}
maybe this can help?
This if for downloading a PDF file which contains some information about a product.
Related
So I am new to this vscode extension api. I have this functionality where I need to take input from the user when they click on certain line and then get the 1). input value, line number and file name and 2). store it to a text file.
I am done with the first part, I am getting the data everything. Now I have to just write it to the file and if there is data already, new data should be appended not overwritten.
I have tried using fs.writeFileSync(filePath, data) and readFileSync but nothing, I do not know if I am doing it correctly. If someone can point me in the right direction I am just blank at this stage?
Any help would be appreciated, Thanks in advance.
The FS node module works fine in an extension. I use it all the time for file work in my extension. Here's a helper function to export something to a file with error handling:
/**
* Asks the user for a file to store the given data in. Checks if the file already exists and ask for permission to
* overwrite it, if so. Also copies a number extra files to the target folder.
*
* #param fileName A default file name the user can change, if wanted.
* #param filter The file type filter as used in showSaveDialog.
* #param data The data to write.
* #param extraFiles Files to copy to the target folder (e.g. css).
*/
public static exportDataWithConfirmation(fileName: string, filters: { [name: string]: string[] }, data: string,
extraFiles: string[]): void {
void window.showSaveDialog({
defaultUri: Uri.file(fileName),
filters,
}).then((uri: Uri | undefined) => {
if (uri) {
const value = uri.fsPath;
fs.writeFile(value, data, (error) => {
if (error) {
void window.showErrorMessage("Could not write to file: " + value + ": " + error.message);
} else {
this.copyFilesIfNewer(extraFiles, path.dirname(value));
void window.showInformationMessage("Diagram successfully written to file '" + value + "'.");
}
});
}
});
}
And here an example where I read a file without user intervention:
this.configurationDone.wait(1000).then(() => {
...
try {
const testInput = fs.readFileSync(args.input, { encoding: "utf8" });
...
} catch (e) {
...
}
...
});
To merge Storage files in Codename One I elaborated this solution:
/**
* Merges the given list of Storage files in the output Storage file.
* #param toBeMerged
* #param output
* #throws IOException
*/
public static synchronized void mergeStorageFiles(List<String> toBeMerged, String output) throws IOException {
if (toBeMerged.contains(output)) {
throw new IllegalArgumentException("The output file cannot be contained in the toBeMerged list of input files.");
}
// Note: the temporary file used for merging is placed in the FileSystemStorage because it offers the method
// openOutputStream(String file, int offset) that allows appending to a stream. Storage doesn't have a such method.
long writtenBytes = 0;
String tempFile = FileSystemStorage.getInstance().getAppHomePath() + "/tempFileUsedInMerge";
for (String partialFile : toBeMerged) {
InputStream in = Storage.getInstance().createInputStream(partialFile);
OutputStream out = FileSystemStorage.getInstance().openOutputStream(tempFile, (int) writtenBytes);
Util.copy(in, out);
writtenBytes = FileSystemStorage.getInstance().getLength(tempFile);
}
Util.copy(FileSystemStorage.getInstance().openInputStream(tempFile), Storage.getInstance().createOutputStream(output));
FileSystemStorage.getInstance().delete(tempFile);
}
This solution is based on the API FileSystemStorage.openOutputStream(String file, int offset), that is the only API that I found to allow to append the content of a file to another.
Are there other API that can be used to append or merge files?
Thank you
Since you end up copying everything to a Storage entry I don't see the value of using FileSystemStorage as an intermediate merging tool.
The only reason I can think of is integrity of the output file (e.g. if failure happens while writing) but that can happen here too. You can guarantee integrity by setting a flag e.g. creating a file called "writeLock" and deleting it when write has finished successfully.
To be clear I would copy like this which is simpler/faster:
try(OutputStream out = Storage.getInstance().createOutputStream(output)) {
for (String partialFile : toBeMerged) {
try(InputStream in = Storage.getInstance().createInputStream(partialFile)) {
Util.copyNoClose(in, out, 8192);
}
}
}
I am writing an Eclipse Plugin which requires me to get full path of any kind of file open in the Workspace.
I am able to get full path of any file which is part of any Eclipse project. Code to get open/active editor file from workspace.
public static String getActiveFilename(IWorkbenchWindow window) {
IWorkbenchPage activePage = window.getActivePage();
IEditorInput input = activePage.getActiveEditor().getEditorInput();
String name = activePage.getActiveEditor().getEditorInput().getName();
PluginUtils.log(activePage.getActiveEditor().getClass() +" Editor.");
IPath path = input instanceof FileEditorInput ? ((FileEditorInput) input).getPath() : null;
if (path != null) {
return path.toPortableString();
}
return name;
}
However, if any file is drag-dropped in Workspace or opened using File -> Open File. For instance, I opened a file from /Users/mac/log.txt from File -> Open File. My plugin is not able to find location of this file.
After couple of days search, I found the answer by looking at the source code of Eclipse IDE.
In IDE.class, Eclipse tries to find a suitable editor input depending on the workspace file or an external file. Eclipse handles files in workspace using FileEditorInput and external files using FileStoreEditorInput. Code snippet below:
/**
* Create the Editor Input appropriate for the given <code>IFileStore</code>.
* The result is a normal file editor input if the file exists in the
* workspace and, if not, we create a wrapper capable of managing an
* 'external' file using its <code>IFileStore</code>.
*
* #param fileStore
* The file store to provide the editor input for
* #return The editor input associated with the given file store
* #since 3.3
*/
private static IEditorInput getEditorInput(IFileStore fileStore) {
IFile workspaceFile = getWorkspaceFile(fileStore);
if (workspaceFile != null)
return new FileEditorInput(workspaceFile);
return new FileStoreEditorInput(fileStore);
}
I have modified the code posted in the question to handle both files in Workspace and external file.
public static String getActiveEditorFilepath(IWorkbenchWindow window) {
IWorkbenchPage activePage = window.getActivePage();
IEditorInput input = activePage.getActiveEditor().getEditorInput();
String name = activePage.getActiveEditor().getEditorInput().getName();
//Path of files in the workspace.
IPath path = input instanceof FileEditorInput ? ((FileEditorInput) input).getPath() : null;
if (path != null) {
return path.toPortableString();
}
//Path of the externally opened files in Editor context.
try {
URI urlPath = input instanceof FileStoreEditorInput ? ((FileStoreEditorInput) input).getURI() : null;
if (urlPath != null) {
return new File(urlPath.toURL().getPath()).getAbsolutePath();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
//Fallback option to get at least name
return name;
}
Is there anyway I can get the last downloaded file using selenium. Currently I am downloading an Excel file using selenium, I need to get that file and read it. the reading part is covered, but I need the downloaded file path and file name in order to read it. So far i haven't found anything which can help. I am looking mainly for a google chrome solution, but firefox works too.
Thanks in advance
You can save your download to a fix location by using the profile. Check these discussions:
Downloading file to specified location with Selenium and python
Access to file download dialog in Firefox
As you have mentioned that you have covered the reading part. You can read it from that fixed location.
Below is the code snippet that can help resolve the above query:
**Changes in driver file:**
protected File downloadsDir = new File("");
if (browser.equalsIgnoreCase("firefox"))
{
downloadsDir = new File(System.getProperty("user.dir") + File.separatorChar + "downloads");
if (!downloadsDir.exists())
{
boolean ddCreated = downloadsDir.mkdir();
if (!ddCreated) {
System.exit(1);
}
}
}
/*Firefox browser profile*/
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.dir", downloadsDir.getAbsolutePath());
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "text/plain,application/octet-stream");
**Empty the download directory[Can be implemented as #BeforeClass]:**
public void emptyDownloadsDir()
{
// Verify downloads dir is empty, if not remove all files.
File[] downloadDirFiles = downloadsDir.listFiles();
if (downloadDirFiles != null) {
for (File f : downloadDirFiles) {
if (f.exists()) {
boolean deleted = FileUtility.delete(f);
assertTrue(deleted, "Files are not deleted from system local directory" + downloadsDir + ", skipping the download tests.");
}
}
}
}
**Check the Latest downloaded file:**
/*Test file*/
protected static String EXCEL_FILE_NAME= Test_Excel_File.xls;
protected static int WAIT_IN_SECONDS_DOWNLOAD = 60;
// Wait for File download.
int counter = 0;
while (counter++ < WAIT_IN_SECONDS_DOWNLOAD && (downloadsDir.listFiles().length != 1 || downloadsDir.listFiles()[0].getName().matches(EXCEL_FILE_NAME))) {
this.wait(2);
}
// Verify the downloaded File by comparing name.
File[] downloadDirFiles = downloadsDir.listFiles();
String actualName = null;
for (File file : downloadDirFiles) {
actualName = file.getName();
if (actualName.equals(EXCEL_FILE_NAME)) {
break;
}
}
assertEquals(actualName, EXCEL_FILE_NAME, "Last Downloaded File name does not matches.");
import os
import glob
home = os.path.expanduser("~")
downloadspath=os.path.join(home, "Downloads")
list_of_files = glob.glob(downloadspath+"\*.pptx") # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)
Simplified solution to get the path to last file in Downloads folder. The above code will get path of the latest .pptx file in Downlodas. Change the extension as required. Or else you can chose not to specify the extension
Note, Shared answer is specific to Chrome Browser and will ONLY return LATEST downloaded file. But we can modify accordingly it for other browsers and for all files as well.
Let say, how we test latest downloaded file in browser.
In existing test browser Open NewTab Window
Go to
downloads (chrome://downloads/)
Check if expected file is there
or not
Now same thing in selenium using java
driver.get("chrome://downloads/");
JavascriptExecutor js = (JavascriptExecutor) driver;
WebElement element = (WebElement) js.executeScript("return document.querySelector('downloads-manager').shadowRoot.querySelector('#mainContainer > iron-list > downloads-item').shadowRoot.querySelector('#content')");
String latestFileName= element.getText();
I have a problem with importing a vendor class in my Cakephp 1.3 project on my server.
I have just upgraded from Ubuntu 12.04 LTS server to Ubuntu 14.04 and I hit this problem: my vendor class in not imported corectly and crashes my whole project.
My error looks like this:
xmlDocument = file_get_contents($url); $this->parseXMLDocument(); } /** * parseXMLDocument method * * #access public * #return void */ function parseXMLDocument() { try { $xml = new SimpleXMLElement($this->xmlDocument); $this->date=$xml->Header->PublishingDate; foreach($xml->Body->Cube->Rate as $line) $this->currency[]=array("name"=>$line["currency"], "value"=>$line, "multiplier"=>$line["multiplier"]); } catch(Exception $e) { pr($e); } } /** * getCurs method * * get current exchange rate: example getCurs("USD") * * #access public * #return double */ function getCurs($currency) { foreach($this->currency as $line) if($line["name"]==$currency) return $line["value"]; return "Incorrect currency!"; } function getValue($currency) { foreach($this->currency as $line) if($line["name"]==$currency) return (String)$line["value"]; return "Incorrect currency!"; } }
Fatal error: Class 'cursBnrXML' not found in /var/www/html/amsrentacar/app/app_controller.php on line 875
The code above the Fatal Error is actually the content of the class that was supposed to get imported using:
App::import('Vendor', 'bnr');
$currency = new cursBnrXML("http://www.bnr.ro/nbrfxrates.xml");
This code still works on my local Ubuntu 14.04 LAMPP powered desktop, but not on the server, and I cannot understand why.
Does anyone here have any ideeas?
I really need to get this working ASAP.