Sitecore PDF Not Downloading - sitecore

I have a couple of unversioned PDFs in the media library... when I try opening them up from their URLs, it says "Layout not found". When I assign a layout (any layout), it just doesn't render anything.
I've added forcedownload=true to the media library section of the web.config... is there anything I'm missing? I thought this was supposed to download by default
http://testsite.org/sitecore/media%20library/pdfs/Publications/Periodicals/Test
The URL above basically doesn't work

Links to items in the media library are usually prefixed with /~/media/, unless you have changed the value of Media.MediaLinkPrefix in config. The link should be something like:
http://testsite.org/~/media/pdfs/Publications/Periodicals/Test.pdf
Make sure you are generating the URLs using MediaManager.GetMediaUrl()
FileField fileField = Sitecore.Context.Item.Fields["File Field"];
var mediaItem = new MediaItem(fileField.MediaItem);
string url = Sitecore.StringUtil.EnsurePrefix('/', MediaManager.GetMediaUrl(fileMediaItem));
Always use LinkManager.GetItemUrl() for items and MediaManager.GetMediaUrl() for media items to generate Sitecore URLs.
http://briancaos.wordpress.com/2012/08/24/sitecore-links-with-linkmanager-and-mediamanager/
http://corecompetency.tohams.com/index.php/linking-to-an-image-or-file-in-the-media-library/

You don't have to assign a layout to media item. Make sure you add "/" prefix before the url. Ex: site/~/media/path to pdf.ashx.
Also make sure you have media files published.

//below is the code to specify an Image URL
MediaItem mediaItem = new MediaItem(Sitecore.Context.Database.GetItem("Path"));
if (mediaItem != null)
{
imgBtn.ImageUrl = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(mediaItem);
imgBtn.AlternateText = mediaItem.Alt;
}

Related

get list of files in a sharepoint directory using python

I have a url for sharepoint directory(intranet) and need an api to return list of files in that directory given the url. how can I do that using python?
Posting in case anyone else comes across this issue of getting files from a SharePoint folder from just the folder path.
This link really helped me do this: https://github.com/vgrem/Office365-REST-Python-Client/issues/98. I found so much info about doing this for HTTP but not in Python so hopefully someone else needs more Python reference.
I am assuming you are all setup with client_id and client_secret with the Sharepoint API. If not you can use this for reference: https://learn.microsoft.com/en-us/sharepoint/dev/solution-guidance/security-apponly-azureacs
I basically wanted to grab the names/relative urls of the files within a folder and then get the most recent file in the folder and put into a dataframe.
I'm sure this isn't the "Pythonic" way to do this but it works which is good enough for me.
!pip install Office365-REST-Python-Client
from office365.runtime.auth.client_credential import ClientCredential
from office365.runtime.client_request_exception import ClientRequestException
from office365.sharepoint.client_context import ClientContext
from office365.sharepoint.files.file import File
import io
import datetime
import pandas as pd
sp_site = 'https://<org>.sharepoint.com/sites/<my_site>/'
relative_url = "/sites/<my_site/Shared Documents/<folder>/<sub_folder>"
client_credentials = ClientCredential(credentials['client_id'], credentials['client_secret'])
ctx = ClientContext(sp_site).with_credentials(client_credentials)
libraryRoot = ctx.web.get_folder_by_server_relative_path(relative_url)
ctx.load(libraryRoot)
ctx.execute_query()
#if you want to get the folders within <sub_folder>
folders = libraryRoot.folders
ctx.load(folders)
ctx.execute_query()
for myfolder in folders:
print("Folder name: {0}".format(myfolder.properties["ServerRelativeUrl"]))
#if you want to get the files in the folder
files = libraryRoot.files
ctx.load(files)
ctx.execute_query()
#create a dataframe of the important file properties for me for each file in the folder
df_files = pd.DataFrame(columns = ['Name', 'ServerRelativeUrl', 'TimeLastModified', 'ModTime'])
for myfile in files:
#use mod_time to get in better date format
mod_time = datetime.datetime.strptime(myfile.properties['TimeLastModified'], '%Y-%m-%dT%H:%M:%SZ')
#create a dict of all of the info to add into dataframe and then append to dataframe
dict = {'Name': myfile.properties['Name'], 'ServerRelativeUrl': myfile.properties['ServerRelativeUrl'], 'TimeLastModified': myfile.properties['TimeLastModified'], 'ModTime': mod_time}
df_files = df_files.append(dict, ignore_index= True )
#print statements if needed
# print("File name: {0}".format(myfile.properties["Name"]))
# print("File link: {0}".format(myfile.properties["ServerRelativeUrl"]))
# print("File last modified: {0}".format(myfile.properties["TimeLastModified"]))
#get index of the most recently modified file and the ServerRelativeUrl associated with that index
newest_index = df_files['ModTime'].idxmax()
newest_file_url = df_files.iloc[newest_index]['ServerRelativeUrl']
# Get Excel File by newest_file_url identified above
response= File.open_binary(ctx, newest_file_url)
# save data to BytesIO stream
bytes_file_obj = io.BytesIO()
bytes_file_obj.write(response.content)
bytes_file_obj.seek(0) # set file object to start
# load Excel file from BytesIO stream
df = pd.read_excel(bytes_file_obj, sheet_name='Sheet1', header= 0)
Here is another helpful link of the file properties you can view: https://learn.microsoft.com/en-us/previous-versions/office/developer/sharepoint-rest-reference/dn450841(v=office.15). Scroll down to file properties section.
Hopefully this is helpful to someone. Again, I am not a pro and most of the time I need things to be a bit more explicit and written out. Maybe others feel that way too.
You need to do 2 things here.
Get a list of files (which can be directories or simple files) in
the directory of your interest.
Loop over each item in this list of files and check if
the item is a file or a directory. For each directory do the same as
step 1 and 2.
You can find more documentation at https://learn.microsoft.com/en-us/sharepoint/dev/sp-add-ins/working-with-folders-and-files-with-rest#working-with-files-attached-to-list-items-by-using-rest
def getFilesList(directoryName):
...
return filesList
# This will tell you if the item is a file or a directory.
def isDirectory(item):
...
return true/false
Hope this helps.
I have a url for sharepoint directory
Assuming you asking about a library, you can use SharePoint's REST API and make a web service call to:
https://yourServer/sites/yourSite/_api/web/lists/getbytitle('Documents')/items?$select=Title
This will return a list of documents at: https://yourServer/sites/yourSite/Documents
See: https://msdn.microsoft.com/en-us/library/office/dn531433.aspx
You will of course need the appropriate permissions / credentials to access that library.
You can not use "server name/sites/Folder name/Subfolder name/_api/web/lists/getbytitle('Documents')/items?$select=Title" as URL in SharePoint REST API.
The URL structure should be like below considering WebSiteURL is the URL of site/subsite containing document library from which you are trying to get files and Documents is the Display name of document library:
WebSiteURL/_api/web/lists/getbytitle('Documents')/items?$select=Title
And if you want to list metadata field values you should add Field names separated by comma in $select.
Quick tip: If you are not sure about the REST API URL formation. Try pasting the URL in Chrome browser (you must be logged in to SharePoint site with appropriate permissions) and see if you get proper result as XML if you are successful then update the REST URL and run the code. This way you will save time of running your python code.

cloudinary direct upload form is not valid, need to re upload

i am using django and cloudinary direct upload to upload iamges
it is working if the form is valid.
but if my form is not valid, my page reloaded, and then the form will ask the user to upload the image again.
any way to solve this?
my code is attached below.
since i use direct upload, after an image is uploaded. it will be displayed immediately on the front end.
but when the form is invalid and the form is refreshed, the image is gone. ( after your latest update, it is true i do not need to re upload the photo again. but the photo is gone. how to display that again?)
thanks.
<script>
$('.cloudinary-fileupload').bind('cloudinarydone', function(e, data) {
var imag_var = $.cloudinary.image(data.result.public_id, {
format : data.result.format,
version : data.result.version,
transformation : 'form_preview'
});
$('.preview').html(imag_var);
$('.status_value').text('Uploaded:' + data.result.public_id);
$('#id_cover_image').val(data.result.public_id);
return true;
});
$('.cloudinary-fileupload').bind('fileuploadprogress', function(e, data) {
$('.progress').attr({
style : "visibility:show",
});
$('.status_value').text('Uploading...');
});
</script>
The Cloudinary javascript plugin puts the preloaded resource URI in a hidden field.
See here.
From the above one sees that if the field already exists the javascript plugin will populate it. Otherwise, it will create it.
In order to retain that URI across invalid form submissions you should create a hidden field named according to the field name you specified for cloudinary_direct_upload_field and which is populated with the value from the failed submission.
Another way to work around the issue would be to submit the form using an AJAX call. That way the data on page is retained even if validation failed and resubmission is possible. See here for an example of how that may be done.
EDIT:
Version 1.0.12 of the Cloudinary Python client library now adds the hidden field when needed out of the box so resubmissions should work. See the change log.
EDIT 2:
In order to regenerate a preview image in case of form validation error you can add something like this to the javascript code you run on page load (assuming the field name in the form is "image"):
//If form validation failed have the posted preloaded URI from the earlier
//submission so we can show preview
//pull the value from the hidden field
var imageUri = $('#direct_upload input[name="image"]').val();
//preloaded image URI structure
//{resource_type}/{type}/v{version}/{filename}#{signature}
var regex = /^([^\/]+)\/([^\/]+)\/v(\d+)\/([^#]+)#([^\/]+)$/;
//if there is value and it matches the pattern:
if (imageUri && regex.test(imageUri)) {
var uriParts = regex.exec(imageUri);
var version = uriParts[3];
var filename = uriParts[4];
//reconstruct a viable source
var src = "v" + version + "/" + filename;
//generate a cloudinary image tag and add it to the 'preview' div
$(".preview").append(
$.cloudinary.image(src, {
transformation: "form_preview" //your named transformation
})
);
}

Get the item matching a URL in Sitecore

In a site I'm building, I'm trying to use the referer to verify AJAX requests are coming from the correct URLs.
To do this I'd like to get Sitecore to resolve a URL to an Item. For example,
http://www.mysite.com/abc/def
might resolve to the item at the path
sitecore/Content/MySite/Home/abc/def
What's the recommended way to go about this in my code?
Thanks for all the answers but none of them did everything I needed. This worked for me.
var url = new Uri(...);
// Obtain a SiteContext for the host and virtual path
var siteContext = SiteContextFactory.GetSiteContext(url.Host, url.PathAndQuery);
// Get the path to the Home item
var homePath = siteContext.StartPath;
if (!homePath.EndsWith("/"))
homePath += "/";
// Get the path to the item, removing virtual path if any
var itemPath = MainUtil.DecodeName(url.AbsolutePath);
if (itemPath.StartsWith(siteContext.VirtualFolder))
itemPath = itemPath.Remove(0,siteContext.VirtualFolder.Length);
// Obtain the item
var fullPath = homePath + itemPath;
var item = siteContext.Database.GetItem(fullPath);
This answer is more for other visitors hitting this SO question. In case of Sitecore 8 you could do this:
new Sitecore.Data.ItemResolvers.ContentItemPathResolver().ResolveItem(<string path>)
Where <string path> is like any local path (or relative url, if you will) string that sitecore would be able to generate for you. When using displayname values instead of item names (possibly the case if you have a multilingual site), this is very handy to actually retrieve the corresponding Item from database.
In my case I use this to show a valid breadcrumb where the parent paths DO have the context language item version added, but the requested page has no context language version to render. Sitecore.Context.Database.GetItem(<string path>) couldn't resolve the displayname-based path, while the ResolveItem method does... searched a day for a good answer on this case.
Questioning myself now, why this isn't used much...?
Maybe it is an expensive query for a site with a big tree. That is something to consider yourself.
Don't really get what you're trying to do (with your AJAX request and such), but if you want http://www.mysite.com/abc/def to resolve the item sitecore/content/MySite/Home/abc/def, you need to configure your <site> in the web.config like this:
<site name="MySite" hostName="www.mysite.com" rootPath="/sitecore/content/MySite" startItem="/Home" *other attributes here* />
You can use the method ItemManager.GetItem(itemPath, language, version, database, securityCheck) To resolve an item based on it's (full)path.

Get image src and alt attribute in Sitecore 6?

I use the following to get, for instance, the header of the current page;
Header = Sitecore.Context.Item["Header"]
But how would i go about getting the src url of a image field?
PictureSrc = Sitecore.Context.Item["MyImage"]
You will want to look at leveraging the Sitecore.Resources.Media.MediaManager to get the URL to a media library item.
Before you get there, get the field from the item and cast it to a FileField. Once you have a FileField you can get access to the MediaItem.
Item item = Sitecore.Context.Item;
Sitecore.Data.Fields.ImageField imgField = ((Sitecore.Data.Fields.ImageField)item.Fields["MyImage"]);
string url = Sitecore.Resources.Media.MediaManager.GetMediaUrl(imgField.MediaItem);
string altText = imgField.Alt;
Link to Sitecore Media Item

Responding with a static file in viewer

I'am developing a django application using Apache+wsgi_mod. I defined a simple viewer returning user's image. But in case the user hasn't any picture I want to render a static standard image (dependent on sex), stored in my static folder. I know I could use static.serve() but django documentation dissuades this. How to serve a static file from a viewer?
UPDATE:
viewer is a method defined in views.py (img below e.g.)
I might want to return HttpResponseRedirect() to my static content. But than I need absolute URL.
I need this because I've got something like that:
def img(request, usr_id):
usr_image = get_usr_image(usr_id)
if usr_image == None:
return respond_with_standard_image()
else:
response = HttpResponse(mimetype='image/jpg')
response.write(usr_image)
return response
and want to respond with a standard user image.
UPDATE2:
I can do something like that:
return HttpResponseRedirect('http://' + request.get_host() + settings.STATIC_URL + 'img/125px-Silver_-_male.png')
but I'm not satisfied.
Django should'nt be involved into rendering images or any other static file. You should put your users images in a custom directory, and serving it directly with your web server.
Rendering a different image if the original file does not exists can easily be achieved with a rewrite rule.