String.Empty as DirectoryName of HttpPostedFileBase - asp.net

I have a controller with action:
[HttpPost]
public ActionResult Add(Question container, HttpPostedFileBase file)
{
if (file != null && file.ContentLength > 0)
{
var clientPath=Path.GetDirectoryName(file.FileName);
and clientpath is "".
I need this because I don't want to save file at my server, but right away sending it to flickr
string photoId = flickr.UploadPicture(clientPath, title, description, "", uploadAsPublic, false, false);
How can I get path of client file?
I'm using FlickrNet library btw.

To send the file directly without first saving it on the server, just use the overloaded method:
string photoId = flickr.UploadPicture(file.InputStream, title, description, "", uploadAsPublic, false, false);

You say you want to send the file directly to Flickr but your code attempts to use the clientpath for this... even if it wasn't empty (which it is because of security!) your code would NOT work... because it would try to use a path which only exists on the client-side of your ASP.NET-app as if it were a path on your server...
What you attempt is AFAIK impossible - what is possible is this:
IF FlickrNet library provides an UploadPicture method accepting a Stream then you can call it with file.InputStream... IF it does not provide such an overload you will have to save the file locally on your server in order to upload it to Flickr!

Related

Download an externalReference from PlannerTask using the Graph API

I'd like to download a file attached to a PlannerTask. I already have the external references but I can't figure out how to access the file.
An external reference is a JSON object like this:
{
"https%3A//contoso%2Esharepoint%2Ecom/sites/GroupName/Shared%20Documents/AnnualReport%2Epptx":
{
// ... snip ...
}
}
I've tried to use the following endpoint
GET /groups/{group-id}/drive/root:/sites/GroupName/Shared%20Documents/AnnualReport%2Epptx
but I get a 404 response. Indeed, when I use the query in Graph Explorer it gives me a warning about "Invalid whitespace in URL" (?).
A workaround that I've found is to use the search endpoint to look for files like this:
GET /groups/{group-id}/drive/root/search(q='AnnualReport.pptx')
and hope the file name is unique.
Anyway, with both methods I need extra information (ie. the group-id) that may not be readily available by the time I have the external reference object.
What is the proper way to get a download url for a driveItem that is referenced by an external reference object in a PlannerTask?
Do I really need the group-id to access such file?
The keys in external references are webUrl instances, so they can be used with the /shares/ endpoint. See this answer for details on how to do it.
When you get a driveItem object, the download url is available from AdditionalData: driveItem.AdditionalData["#microsoft.graph.downloadUrl"]. You can use WebClient.DownloadFile to download the file on the local machine.
Here is the final code:
var remoteUri = "https%3A//contoso%2Esharepoint%2Ecom/sites/GroupName/Shared%20Documents/AnnualReport%2Epptx";
var localFile = "/tmp/foo.pptx";
string sharingUrl = remoteUri;
string base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sharingUrl));
string encodedUrl = "u!" + base64Value.TrimEnd('=').Replace('/','_').Replace('+','-');
DriveItem driveItem = m_graphClient
.Shares[encodedUrl]
.DriveItem
.Request()
.GetAsync().Result;
using (WebClient client = new WebClient())
{
client.DownloadFile(driveItem.AdditionalData["#microsoft.graph.downloadUrl"].ToString(),
localFile);
}

How to get the Filename in code behind on selecting a file, before uploading it to the server using aspx and CS?

I want to retrieve the file name and perform some validation on that filename. so before uploading i have to get the filename of the file selected for uploading.
Actually what i wanted is to get the filename and retrieve some fields from database based on which file is chosen , and send the data retrieved from database on the client side in some textfield. So for that before on click of upload i need to call a method in code behind which will validate all these things. I tried using AjaxControlToolkit, its not working.
Use GetFileName() method. Below example from MSDN link.
string fileName = #"C:\mydir\myfile.ext";
string path = #"C:\mydir\";
string result;
result = Path.GetFileName(fileName);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
fileName, result);
result = Path.GetFileName(path);
Console.WriteLine("GetFileName('{0}') returns '{1}'",
path, result);
// This code produces output similar to the following:
//
// GetFileName('C:\mydir\myfile.ext') returns 'myfile.ext'
// GetFileName('C:\mydir\') returns ''
If you want to validate the filename on the client prior to sending it to the server you will not be able to do so with C#, you could quite easiy write a validation function in Javascript however.
You could perform server side validation of the file, but that would mean after uploading it. You could then make sure the file fulfills all your validation criterias and if it for some reason fails validation you could return the error message to the user. But that would mean a full postback of the page.
See below code example to get the file name :
var filePath = "C:\\SpiderCode\\MyFile.txt";
var fileName = System.IO.Path.GetFileName(filePath);
Client Side Code
<asp:FileUpload runat="server" ID="FileUpload" Width="100px" />
In code behind, check if user select any file, then it will simply gives you the file name in the fileName variable.
if (FileUpload.HasFile)
{
string fileName = FileUpload.FileName;
}

Images are getting published with TCM id appended with the image name

Mode of publishing - static
I'm trying to publish images, but the issue is whenever I publish those images, their TCM URI is appended to their name (i.e if image name is example and its TCM URI is like tcm:1-115, image filename becomes example_tcm1-115).
I have written the following code:
public void Transform(Engine engine, Package package)
{
Filter MMCompFilter = new Filter();
MMCompFilter.Conditions["ItemType"] = Tridion.ContentManager.ItemType.Component;
Folder folder = engine.GetObject("tcm:1-1-2") as Folder;
foreach (Component MMcomp in folder.GetItems(MMCompFilter))
{
Binary binary = engine.PublishingContext.RenderedItem.AddBinary(MMcomp);
String binaryurl = binary.Url;
char[] array = binaryurl.ToCharArray();
Array.Reverse(array);
string obj = new string(array);
string final = newImagepath(obj);
char[] array2 = final.ToCharArray();
Array.Reverse(array2);
string obj2 = new string(array2);
package.PushItem("Image", package.CreateHtmlItem(obj2));
}
public string newImagepath(string filePath)
{
int formatIndex =filePath.IndexOf(".");
string format= filePath.Substring(0,formatIndex);
int finalPath=filePath.IndexOf("_");
string newPath=filePath.Substring((finalPath+1));
return (format+"."+newPath);
}
}
I want to publish images without the TCM URI appended to it. Plz suggest how can it be done.
Chris Summers wrote a very nice article on this very topic http://www.urbancherry.net/blogengine/post/2010/02/09/Unique-binary-filenames-for-SDL-Tridion-Multimedia-Components.aspx
It is basically a very simple thing to fix, but can have huge consequences which you should be aware of!
You can only publish a binary with a certain file-name in a single location once (and a binary can only be published to a single location on the presentation server, unless you publish it as a variant). However, in the CMS it is very easy to create Multimedia Components with the same binary file-name in different folders, which if they get published to the same location will be in conflict. That is why by default SDL Tridion appends the TCM URI to the filename to make it unique.
Simplest is always best.
In your TBB, just push the individual images to the package:
package.PushItem(package.CreateMultimediaItem(component.Id));
Then use the "PublishBinariesInPackage" TBB to publish these images to your presentation server.
You can use the RenderedItem.AddBinary method for this goal. Some of the overloaded versions of the method allows to publish an image as a stream, and pass any file name. For example:
public Binary AddBinary(
Stream content,
string filename,
string variantId,
string mimeType
)

ASP.NET Photo Upload

When uploading a photo to my server using the following code, I'm receiving an erroneous value. This is working fine in the debug mode and when published in localhost.
string filePath = Path.Combine(HttpContext.Server.MapPath("../Uploads"), date);
if (!Directory.Exists(HttpContext.Server.MapPath("../Uploads")))
{
Directory.CreateDirectory(HttpContext.Server.MapPath("../Uploads"));
}
file.SaveAs(filePath);
Can someone please point out what I've done incorrectly?
ok I am assuming that you are using File Upload control or you can use the below sample code if you want to use the FileUpload control in your asp.net page.
Add the FileUpload control (Here im adding ajax async FileUpload control and named as asyncFileUpload.
Write A Method and Call it whenever you want.
public int AsyncFileUpload()
{
string xlsFile = AsyncFileUpload1.FileName;
if (AsyncFileUpload1.HasFile)
{
string FileName = Path.GetFileName(AsyncFileUpload1.PostedFile.FileName);
string Extension = Path.GetExtension(AsyncFileUpload1.PostedFile.FileName);
string FilePath = Server.MapPath("~/Uploads/" + FileName);
if (Extension == ".doc")//check the file extension here
{
AsyncFileUpload1.SaveAs(FilePath);
}
}
}

how to make a picture file downloadable?

I have an ASP.NET MVC3 application and I want to link_to an image file (png, jpeg, gif, etc), and when user clicks on it, the file goes to download, instead of the browser shows it; is there any way to do this?
take your link something like this:
#Html.ActionLink(
"Download Image", // text to show
"Download", // action name
["DownloadManager", // if need, controller]
new { filename = "my-image", fileext = "jpeg" } // file-name and extension
)
and action-method is here:
public FilePathResult Download(string filename, string fileext) {
var basePath = Server.MapPath("~/Contents/Images/");
var fullPath = System.IO.Path.Combine(
basePath, string.Concat(filename.Trim(), '.', fileext.Trim()));
var contentType = GetContentType(fileext);
// The file name to use in the file-download dialog box that is displayed in the browser.
var downloadName = "one-name-for-client-file." + fileext;
return File(fullPath, contentType, downloadName);
}
private string GetContentType(string fileext) {
switch (fileext) {
case "jpg":
case "jpe":
case "jpeg": return "image/jpeg";
case "png": return "image/x-png";
case "gif": return "image/gif";
default: throw new NotSupportedException();
}
}
UPDATE:
in fact, when a file is sending to a browser, this key/value will be generated in http-header:
Content-Disposition: attachment; filename=file-client-name.ext
which file-client-name.ext is the name.extension that you want the file save-as it on client system; for example, if you want to do this in ASP.NET (none mvc), you can create a HttpHandler, write the file-stream to Response, and just add the above key/value to the http-header:
Response.Headers.Add("Content-Disposition", "attachment; filename=" + "file-client-name.ext");
just this, enjoy :D
Well technically your browser is downloading it.
I don't think you can directly link to an image, and have the browser prompt to download.
You could try something where instead of linking directly to the image, you link to a page, which serves up the image in a zip file perhaps - which of course would prompt the download to occur.
Yes, you can.
Now, you'll need to customize this to suit your needs, but I created a FileController that returned files by an identifier (you can easily return by name).
public class FileController : Controller
{
public ActionResult Download(string name)
{
// check the existence of the filename, and load it in to memory
byte[] data = SomeFunctionToReadTheFile(name);
FileContentResult result = new FileContentResult(data, "image/jpg"); // or whatever it is
return result;
}
}
Now, how you read that file or where you get it from is up to you. I then created a route like this:
routes.MapRoute(null, "files/{name}", new { controller = "File", action = "Download"});
My database has a map of identifiers to files (it's actually more complex than this, but I am omitting that logic for brevity), I can write urls like:
"~/files/somefile"
And the relevant file is downloaded.
I don't think this is possible but a simple message saying right click to save image would suffice I think.

Resources