how to make a picture file downloadable? - asp.net

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.

Related

MVC 5 attachment View/Download functionality

This may seem obvious but I'm having a hard time finding the answer.
I have a List of file paths which are stored as relative file paths.
("~\Data\1f492f55-c7ad-44ae-8cbc-93885ac4383a.jpg")
These files can be jpgs,docs or PDFs.
How can I give a View functionality?
You may use the File method to render content of a file (PDF /JPG etc..)
public ActionResult Index()
{
var filePath = #"C:\\temp\tempFile.pdf";
return File(filePath, "application-pdf", "YourFriendlyFileName.pdf");
}
You may change the code the get the file paths and replace it with the hardcoded file path above.
Upload them to the application and use relative path.
As localhost:80/images/image1.jpg
Found the below solution.This support any file types.
public FileResult Download(int id)
{
var filePath = #"~\\Data\0e383d46-021d-48b4-9f03-e9a70bc894f7.jpg";
//var filePath = #"~\\Data\\file.pdf";
//var filePath = #"~\\Data\\word.docx";
string fileName = Path.GetFileName(careTakerFile.FilePath);
return File(filePath, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
}

How do I upload a file to an Acumatica Screen through HTTP virtual path?

How do I upload a file to an Acumatica Screen through HTTP virtual path?
For example, I would like to upload mysite.com/files/abc.pdf to the Sales orders screen.
Below is a code snippet to achieve your goal.It is reading file from HTTP URL and attaching it to one of the existing Case.
//Graph for file management
PX.SM.UploadFileMaintenance filegraph = PXGraph.CreateInstance<PX.SM.UploadFileMaintenance>();
//Since you need file from HTTP URL - below is a sample
WebRequest request = WebRequest.Create("http://www.pdf995.com/samples/pdf.pdf");
using (System.IO.Stream dataStream = request.GetResponse().GetResponseStream())
{
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
dataStream.CopyTo(mStream);
byte[] data = mStream.ToArray();
//Create file info, you may check different overloads as per your need
PX.SM.FileInfo fileinfo = new PX.SM.FileInfo("case.pdf", null, data);
if (filegraph.SaveFile(fileinfo))
{
if (fileinfo.UID.HasValue)
{
// To attach the file to case screen - example
CRCaseMaint graphCase = PXGraph.CreateInstance<CRCaseMaint>();
//Locate existing case
graphCase.Case.Current = graphCase.Case.Search<CRCase.caseCD>("<Case to which you want to attach file>");
//To Attach file
PXNoteAttribute.SetFileNotes(graphCase.Case.Cache, graphCase.Case.Current, fileinfo.UID.Value);
//To Attach note
PXNoteAttribute.SetNote(graphCase.Case.Cache, graphCase.Case.Current, "<Note you wish to specify>");
//Save case
graphCase.Save.Press();
}
}
}
}

Tridion 2009 SP1: Is it possible to publish a .htaccess file?

I am using ISAPI rewrite on a project and would like to know if it is possible to publish a .htaccess file from Tridion?
I have tried creating a Page Template with the .htaccess extension but can't create a page with no name.
Any ideas?
Could I use a C# TBB to change the page name?
I would also choose to use a binary to achieve this, but if you want to manage the htaccess file using text, rather than as a multimedia component, you can push a binary into your package using the following technique:
1) Push the text of the Htaccess file into the package with an accessible name (i.e. Binary_Text)
2) Use code similar to the following to create a text file from the text in the variable and add it to the package
class publishStringItemAsBinary : ITemplate
{
public void Transform(Engine engine, Package package)
{
TemplatingLogger log = TemplatingLogger.GetLogger(typeof(publishStringItemAsBinary));
TemplateUtilities utils = new TemplateUtilities();
System.IO.Stream inputStream = null;
try
{
string strInputName = package.GetValue("InputItem");
string strFileName = package.GetValue("strFileName");
string sg_Destination = package.GetValue("sg_Destination");
string itemComponent = package.GetValue("mm_Component");
inputStream = new MemoryStream(Encoding.UTF8.GetBytes(package.GetValue(strInputName)));
log.Debug("InputObject:" + strInputName);
log.Debug("Filename for binary:" + strFileName);
log.Debug("Destination StructureGroup:" + sg_Destination);
Publication contextPub = utils.getPublicationFromContext(package, engine);
TcmUri uriLocalSG = TemplateUtilities.getLocalUri(new TcmUri(contextPub.Id), new TcmUri(sg_Destination));
TcmUri uriLocalMMComp = TemplateUtilities.getLocalUri(new TcmUri(contextPub.Id), new TcmUri(itemComponent));
StructureGroup sg = (StructureGroup)engine.GetObject(uriLocalSG);
Component comp = (Component)engine.GetObject(uriLocalMMComp);
String sBinaryPath = engine.PublishingContext.RenderedItem.AddBinary(inputStream, strFileName, sg, "nav", comp, "text/xml").Url;
//Put a copy of the path in the package in case you need it
package.PushItem("BinaryPath", package.CreateStringItem(ContentType.Html, sBinaryPath));
}
catch (Exception e)
{
log.Error(e.Message);
}
finally
{
if (inputStream != null)
{
inputStream.Close();
}
}
}
}
I think the code is pretty self explanatory. This publishes a binary of type text/xml, but there should be no issue converting it to do a plain text file.
I think you can use multimedia component to store your .htaccess. Even if you will not be able to upload file without name (Windows limitation), you will be able to change filename later, by modifying BinaryContent.Filename property of multimedia component. You can then publish this component seperately, or use AddBinary method in one of your templates.
There's also a user schema where you can change some other rules: "\Tridion\bin\cm_xml_usr.xsd", but you will not be able to allow empty filenames

String.Empty as DirectoryName of HttpPostedFileBase

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!

How do I format a URI when binding an Image in Silverlight?

I haven't been able to find an answer to this.
I have a database that has image paths in it ("images/myimage.jpg"). These images exist on my asp.net site which is also where I host the SL. I want to bind these images to my ListBox control so that the image displays.
I have read that since I have a string value, "images/myimage.jpg", that I need to convert it to a BitMap image. I have done this:
The xaml:
<Image Source="{Binding ImageFile, Converter={StaticResource ImageConverter}}"/>
The ImageConverter class:
public object Convert(object value, Type targetType,
object parameter, CultureInfo culture)
{
try
{
Uri source= new Uri(value.ToString());
return new BitmapImage(source);
}
catch(Exception ex)
{
return new BitmapImage();
}
}
I get an error when creating the URI, "The Format of the URI could not be determined". What am I doing wrong? If I create a Uri that looks like this: http://localhost:49723/images/myimage.jpg, it works just fine.
Why doesn't just "images/myimage.jpg" work?
A simple, dynamic approach that will work regardless of where your XAP file is located is similar to the following.
//Get the root path for the XAP
string src = Application.Current.Host.Source.ToString();
//Get the application root, where 'ClientBin' is the known dir where the XAP is
string appRoot = src.Substring(0,src.IndexOf("ClientBin"));
//Create the image / uri
BitmapImage img = new BitmapImage();
img.UriSource = new Uri(appRoot + "/Images/myImage.png", UriKind.Relative);
Does this help?
Relative paths to media in Silverlight are wacky so they can work the same (wacky) way that WPF paths do. Relative paths are relative to the XAP file, not the app root.
One trick is to move your XAP to the root of your website, so media paths will be relative to the root.
See my post on relative URI's in Silverlight here.
Just ran into this problem today myself and fixed it the way Jon describes above (without seeing your post though. Could have saved me some time.) I'd also point out that the specific error can be resolved by using the overload:
Uri source = new Uri("Path/Image.jpg", UriKind.Relative);
You'd still be unable to access the images subdirectory without moving the XAP file, but it resolves the error message. At that point the program just happily returns an image with no content, leaving you to use Fiddler or Web Dev Helper to figure out the real problem.
http://www.silverlightexamples.net/post/How-to-Get-Files-From-Resources-in-Silverlight-20.aspx
Resource, and Never Copy on the image, then use "SLapplicationName;component/mypathtoimage/image.png"
using System.Windows.Resources; // StreamResourceInfo
using System.Windows.Media.Imaging; // BitmapImage
....
StreamResourceInfo sr = Application.GetResourceStream(
new Uri("SilverlightApplication1;component/MyImage.png", UriKind.Relative));
BitmapImage bmp = new BitmapImage();
bmp.SetSource(sr.Stream);
You can simply write a method that gives you full server address (protocol://server:port/) and use it to create absolute URLs:
public class Helper{
public static string ServerAddress{
get{
if (_server == "")
_server = _ServerAddress();
return _server;
}
}
private static string _ServerAddress(){
HttpContext ctx = HttpContext.Current;
if (ctx == null) return "";
HttpRequest request = ctx.Request;
if (request == null) return "";
string srvr = request.ServerVariables["SERVER_NAME"];
string port = string.IsNullOrEmpty(request.ServerVariables["SERVER_PORT"])?
"" : ":" + request.ServerVariables["SERVER_PORT"];
string protocol = "http://";//request.ServerVariables["SERVER_PROTOCOL"];
return string.Format("{0}{1}{2}{3}", protocol, srvr, port,
request.ApplicationPath);
}
}
and change you Converter method line:
Uri source= new Uri(value.ToString());
to
if(!string.IsNullOrEmpty(value.ToString()))
Uri source= new Uri(Helper.WebAddress + value.ToString());

Resources