I have set:
MEDIA_URL='/media/'
MEDIAFILES_DIRS = [os.path.join(BASE_DIR, "media_in_pro")]
I have a directory media_in_pro in base directory of project and within this i have directory called "profile" like "media_in_pro/profile/image.jpeg". I have added in my urls static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) to URL_PATTERS.
My problem is when I try to access this image in template like this:
img src="{% media 'profile_image/profile.jpg' %}"
then it raises TemplateSyntaxError because of this media. It does not recognize "media" in img tag.While my static files are working fine and i have used same method for my static files. While i am using static in the same way without any problem. Can anyone help me in sorting this out?
Related
I have some css&js files in my project and I used the BuildBundlerMinifier NuGet package to minify and obfuscate them.
For example, the app.js will minify and obfuscate into app.min.js in the same directory.
Now I want the user can access the app.min.js but can't access the app.js.
I do this for I don't want anybody else to access the source code of my js.
Although someone still can get its source code from the app.min.js while I don't want them to get it easily.
I tried to use FileExtensionContentTypeProvider in Configure of startup.cs to achieve this:
var provider = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
provider.Mappings.Remove(".js");
provider.Mappings.Add(new KeyValuePair<string, string>(".min.js", "application/javascript"));
app.UseStaticFiles(new StaticFileOptions()
{
ContentTypeProvider=provider
});
However, after it runs I can access neither app.js nor app.min.js.
What's wrong with my code?
Thank you.
The FileExtensionContentTypeProvider is only meant to provide a mapping from file extension to the correct MIME type. In order to retrieve the file extension from a file name, it will do the following:
private static string? GetExtension(string path)
{
int index = path.LastIndexOf('.');
if (index < 0)
return null;
return path.Substring(index);
}
It will take the very last part of the extension. So with app.min.js, the reported file extension will still be .js and not .min.js, and as such the mapping for .js will be required.
Modifying the MIME type mapping in order to disallow certain file extensions is probably not the best strategy. It would be better to modify the underlying file provider itself to handle that.
Alternatively, if you want to prevent access to non-minified JavaScript files, you could also split the middleware to conditionally prevent serving static files for any request to a path that ends with .js that is not a .min.js:
app.UseWhen(ctx => !ctx.Request.Path.HasValue
|| !ctx.Request.Path.Value.EndsWith(".js")
|| ctx.Request.Path.Value.EndsWith(".min.js"), app2 =>
{
app2.UseStaticFiles();
});
I want to import a JSON file to use it, I need it to modify it in the future so I put it in public folder not assets, When I refer to it like this import JSON from ../../public/Data.json it works but I don't think so after building project can be resolved because after building there is no public folder. So I tried this :
let addr = process.env.BASE_URL;
import JSON from `${addr}Data.json`;
But It throws an error : SyntaxError
I'm confused now which way is the best and is there another way ?
The assets in the public folder are copied as is to the root of the dist folder. In your code, you can reference it just as /Data.json (if your app is deployed at the root of the domain).
E.g
async someMethod() {
const baseUrl = process.env.BASE_URL;
const data = await this.someHttpClient.get(`${ baseUrl }/Data.json`);
}
If you want to import the JSON as you have tried, I suggest to put it somewhere in the src folder and import from there
E.g.
import data from '#/data/someData.json'
console.log(data);
I came across this because I was doing a stand alone SPA that I wanted to run with no DB and keep the config in a JSON file. The import statement above works great for a static conf file, but anything imported like that gets compiled with the build, so even though your someData.json will exist in the public folder you won't see any changes in your dist because it's actually reading a JS compiled file.
To get around this I:
Convert the JSON file into a simple JS variable in a conf.js file:
e.g.
var srcConf={'bGreatJSON':true};
In index.html, did
<script src='./conf.js'>
Now that the JS variable has been declared in my Vue component I can just look for the window.srcConf and assign it if it exists in mounted or created:
if(typeof window.srcConf!='undefined')
this.sConf=window.srcConf;
This also avoids the GET CORS issue that others posts I've seen runs into, even in the same directory I kept getting CORS violations trying to do an axios call to read the file.
I am using the code below to try and bundle a pre-minified version of the jQuery simpleModal plugin in an ASP.NET MVC4 project:
public static void RegisterBundles(BundleCollection bundles)
{
AddDefaultIgnorePatterns(bundles.IgnoreList);
bundles.Add(new ScriptBundle("~/ModalBundle").Include("~/Scripts/jquery.simplemodal.{version}.min.js"));
}
where AddDefaultIgnorePatterns() is defined as per ASP.NET MVC 4 ScriptBundle returns empty:
public static void AddDefaultIgnorePatterns(IgnoreList ignoreList)
{
if (ignoreList == null)
throw new ArgumentNullException("ignoreList");
ignoreList.Clear();
ignoreList.Ignore("*.intellisense.js");
ignoreList.Ignore("*-vsdoc.js");
ignoreList.Ignore("*.debug.js", OptimizationMode.WhenEnabled);
//ignoreList.Ignore("*.min.js", OptimizationMode.WhenDisabled);
ignoreList.Ignore("*.min.css", OptimizationMode.WhenDisabled);
}
Unfortunately, the requested resource is never included when rendered using #Scripts.Render() after being registered in Application_Start().
The following combinations do seem to work, but where possible I did not want to have to change the file name across a large number of projects:
jquery.simplemodal.1.2.3.min.js (exact version match)
jquery.simplemodal.{version}.js (removal of '.min', with corresponding file rename)
The following do not work:
jquery.simplemodal-{version}.min.js (hyphen before version, with corresponding file rename)
jquery.simplemodal* (loose wildcard, which is very suspicious)
I have verified that the file definitely exists in the expected location, but must be missing something else fundamental. None of my other script or style bundles suffer from this problem. Any ideas?
If you want to use the bundle system you must not use minified files.
When you are un debug mode, your system will load normal files.
When you are in release mode, your system will mingnify it automatically.
you can look a working configuration here :
https://myprettycms.codeplex.com/SourceControl/latest#MyPrettyCMSCommunityManager/Portals/MVC4Portal/App_Start/BundleConfig.cs
I'm creating a single pdf file that I'd like to link to other files in the same directory as the pdf.
ie.
MyFolder
|
|-main.pdf
|-myotherpdf.pdf
|-myotherotherpdf.pdf
I'd like the main.pdf to have links that would cause the default program on the pdf to open the other pdfs.
As I am generating these file on a server and then providing them in a download to the client I cannot use absolute links as these would not exist on the client pc.
So firstly do pdf files actually support relative file links like this, I haven't found much that says they do either way.
Additionally to generate my pdf I'm using abcpdf and providing it html to convert to pdf.
To try and generate the correct out the correct urls in html I have tried the following
<a href='test.pdf'>test pdf link to local file</a>
<a href='#test.pdf'>test pdf link to local file</a>
<a href='/test.pdf'>test pdf link to local file</a>
<a href='file:///test.pdf'>test pdf link to local file</a>
<a href='file://test.pdf'>test pdf link to local file</a>
Most of them either direct to me a point where the pdf document was generated from (temporary file path) or they link hovering shows "file:///test.pdf" in acrobat but clicking it causes a warning dialog to popup asking to allow/deny, upon clicking allow it opens up in firefox with the url "file:///test.pdf" which wouldn't resolve to anything.
Any ideas on how to get this working or if this kind of linking is even possible in pdfs?
I can only answer your question: does PDF files actually support relative file links like this?
Yes, it does. I created a little test with a main.pdf that has two links to two other PDF documents in the same folder. I created the links manually with Acrobat and associated a launch action with the link annotation. See the internal structure here:
Here is the zip with the main plus two secondary PDFs. Note that you can copy them anywhere and the relative links remain valid.
https://www.dropbox.com/s/021tvynkuvr63lv/main.zip
I am not sure how you would accomplish this with abcpdf, especially since you are converting from HTML which probably limits the PDF features available.
So I got it working in the end thanks to #Frank Rem and some help from the abcpdf guys
Code is as follows
foreach (var page in Enumerable.Range(0, doc.PageCount))
{
doc.PageNumber = page;
var annotEnd = doc.GetInfoInt(doc.Page, "Annot Count");
for (var i = 0; i <= annotEnd; ++i)
{
var annotId = doc.GetInfoInt(doc.Page, "Annot " + (i + 1));
if (annotId > 0)
{
var linkText = doc.GetInfo(annotId, "/A*/URI*:Text");
if (!string.IsNullOrWhiteSpace(linkText))
{
var annotationUri = new Uri(linkText);
if (annotationUri.IsFile)
{
// Note abcpdf temp path can be changed in registry so if this changes
// will need to rewrite this to look at the registry
// http://www.websupergoo.com/helppdfnet/source/3-concepts/d-registrykeys.htm
var abcPdfTempPath = Path.GetTempPath() + #"AbcPdf\";
var relativePath = annotationUri.LocalPath.ToLower().Replace(abcPdfTempPath.ToLower(), string.Empty);
// Only consider files that are not directly in the temp path to be valid files
// This is because abcpdf will render the document as html to the temp path
// with a temporary file called something like {GUID}.html
// so it would be difficult to tell which files are the document
// and which are actual file links when trying to do the processing afterwards
// if this becomes and issue this could be swapped out and do a regex on {GUID}.html
// then the only restriction would be that referenced documents cannot be {GUID}.html
if (relativePath.Contains("\\"))
{
doc.SetInfo(annotId, "/A*/S:Name", "Launch");
doc.SetInfo(annotId, "/A*/URI:Del", "");
doc.SetInfo(annotId, "/A*/F:Text", relativePath);
doc.SetInfo(annotId, "/A*/NewWindow:Bool", "true");
}
}
}
}
}
}
This will allow each link to be opened in the viewer that is associated with it on the pc.
I am trying to upload a file in Zend framework. I have following code in my form:
$this->addElementPrefixPath('App', 'App/');
$this->setName('upload');
$this->setAttrib('enctype', 'multipart/form-data');
$description = new Zend_Form_Element_Text('description');
$description->setLabel('Description')
->setRequired(true)
->addValidator('NotEmpty');
$file = new Zend_Form_Element_File('file');
$path="/images";
$file->setDestination($path)
->setLabel('File')
->setRequired(true)
->addValidator('NotEmpty');
$submit = new Zend_Form_Element_Submit('submit');
$submit->setLabel('Upload');
$this->addElements(array($description, $file, $submit));
I am using netbeans and I have one folder named images under public folder. I want that all files are uploaded into images folder but when I run the project it gives the error as
The given destination is not a directory or does not exist
If I give the full path as C:\Users\398853\Documents\NetBeansProjects\ZendWithFileUpload\public\images then it runs fine and the file gets uploaded into images folder. But when I give $path='/images' It says above error'Why? What should be the path given?Thanks.
In SetDestination should be setted absolute path to desitnation folder (/var/www/... or c:/webserver/... in case when you win-user).
But good practice is to get absolute path with functions getcwd() or realpath(dirname(FILE)).
So, at first you shoud define constant (for example with name PUBLIC_PATH) in index.php file (usually situated in public-folder).
defined('PUBLIC_PATH')
|| define('PUBLIC_PATH', realpath(dirname(__FILE__)));
This way you can use variable PUBLIC_PATH instead of writting string "/var/www/..." as prefix to your real path to upload folder.
So, if your "images" folder situated in "public" folder, you should user such construction:
$file->setDestination(PUBLIC_PATH . '/images');
This code also will work after upload project from localhost to webserver.
add config to module.config.php
return array (
....
//other settings
'module_config' => array(
'upload_location' => __DIR__.'/../../../data/uploads'
)
);
add controller
public function getFileUploadLocation() {
$config = $this->getServiceLocator()->get('config');
return $config['module_config']['upload_location'];
}
and use
....
$uploadPath = $this->getFileUploadLocation();
$adapter->setDestination($uploadPath);
....
In your bootstrap code, you need to set your application's root folder.
Whenever you want to get the path of a subfolder in your application folder (eg. images in your scenario), you need to use this variable and append your folder name.
If your bootstrap code is in the Application folder which is under the public root folder,
Zend_Registry::set('APP_ROOT', dirname(dirname(__FILE__)));
In other places of your application, when you want get a folder path, like you want to get the image folder path under the public folder, u need to use,
Zend_Registry::get('APP_ROOT') . "/images";