I lost a lot of time on this issue so i will go straight to topic.
I am receiving empty pdf with correct number of (blank)pages. My action is:
public FileResult DownloadDoc()
{
//Authorization
//initialising filename
//getting content
return File(Convert.FromBase64String(content), "application/pdf", filename);
}
Content is Base64 string and it is correct. I know because when i use system.io.file.writeallbytes to make document i'm getting correct one.
I also tried to return file over Response and result is the same.
There are no (I hope) razor syntax errors.
This part of code used to work, and he stopped despite no one made no change. Maybe IIS was restarted.
If anyone can tell me what else to try ... tnx
p.s. I am looking for way without saving doc on server side.
Sorry,
an error was in javascript that saves file after returning from the server.
If you have similar issues check inner properties of the Blob object!
Related
I am trying to download an image and displaying it in a view in rails.
The reason why I want to download it is because the url contains some api-keys which I am not very fond of giving away.
The solution I have tried thus far is the following:
#Model.rb file
def getUrlMethod
someUrlToAPNGfile = "whatever.png"
file = Tempfile.new(['imageprependname', '.png'], :encoding => "ascii-8bit")
file.write(open(data).read)
return "#{Rails.application.config.action_mailer.default_url_options[:host]}#{file.path}"
end
#This seems to be downloading the image just fine. However the url that is returned does not point to a legal place
Under development I get this URL for the picture: localhost:3000/var/folders/18/94qgts592sq_yq45fnthpzxh0000gn/T/imageprependname20130827-97433-10esqxh.png
That image link does not point anywhere useful.
My theories to what might be wrong is:
The tempfile is deleted before the user can request it
The url points to the wrong place
The url is not a legal route in the routes file
A am currently not aware of any way to fix either of these. Any help?
By the way: I do not need to store the picture after I have displayed it, as it will be changing constantly from the source.
I can think of two options:
First, embed the image directly in the HTML documents, see
http://www.techerator.com/2011/12/how-to-embed-images-directly-into-your-html/
http://webcodertools.com/imagetobase64converter
Second, in the HTML documents, write the image tag as usual:
<img src="/remote_images/show/whatever.png" alt="whatever" />
Then you create a RemoteImages controller to process the requests for images. In the action show, the images will be downloaded and returned with send_data.
You don't have to manage temporary files with both of these options.
You can save the file anywhere in the public folder of the rails application. The right path would be something like this #{Rails.root}/public/myimages/<image_name>.png and then you can refer to it with a URL like this http://localhost:3000/myimages/<image_name>.png. Hope this will help.
I have string data in the form
http://site.com/location
file://server/folder/
I am showing the data as links so clicking on the link takes you to the appropriate web site or file location. Clicking on a link built from 'http://...' data works fine but I get an 'unable to display web page' message when I click on a link built from 'file://' data.
I'm building the link using Html.ActionLink, passing the data as a parameter to a HandleLink method on the controller. The HandleLink method just does Redirect(data). I know the data is coming in correctly because I can copy the incoming value in the debugger and paste in in the address bar of my browser and that works as expected.
How can I make the 'file://' links work correctly?
EDIT: I botched the first question I asked here -- I hope they have a badge for that. The 'file://...' data items are to a folder, not a specific file. Does that make any difference?
As mentioned above, you can't use file:\ to get files on a remote server however you can serve the files using something like the following:
public FileContentResult GetFile(int fileID)
{
string fileName = GetFileNameFromID(fileID); //Retruns path and filename on server
string contentType = "text/csv"; //or other appropriate type
return new FilePathResult(fileName, contentType);
}
Much more info here
My program is dealing with emails which arrive as files (something.eml). In some circumstances I need to amend an attachment and then resave the file. I've been using the instructions here as a basis for my code, but there's no suggestion for trying to do exactly what I'd like. The code I have below successfully removes the original attachment and then tries to add in a new one.
#email.without_attachments!
#email.add_file(amended_version)
Unfortunately it goes wrong in two places. Firstly it seems to remove all mime parts, not just attachments. Any text/plain sections are also ditched. Secondly, if I test by reloading my amended .eml file, the attachment is no longer recognised, despite being in the file.
I've included a gist which includes the original and amended files from my current method.
Is there a better way to do this? Perhaps a way of replacing the attachment directly rather than get rid of it and adding again?
I don't know enough about mail formatting to know why this works, but it does.
I extracted just the line I was interested in from the without_attachments! method and it now seems to work fine. The non-attachment parts of the message are kept intact and the message re-reads fine. Code now reads....
#email.parts.delete_if { |p| p.attachment? }
#email.add_file(amended_version)
I found this. It seems kind of ugly to just throw this into environment.rb. The question is kind of old. I just wanted to ask if there was a better way to do this now.
The problem (if you don't want to click through), is including your custom log message formatter. (The problem I'm solving is that I want to assign a guid to every request, prepend all log messages from that request with the guid, and then return the guid in meta data to the client a.k.a. request id)
Rails logger format string configuration
You can put it in an initializer.
Initializers can be any name and go in config/initializers. Every file in this directory is loaded at startup; it's a great place to put miscellaneous startup code that doesn't seem to fit anywhere else.
Setup:
I am writing the Admin utility for an eLearning Package. Using this utility, the Tutors can write their courses, add/upload images, etc.
My problem is regarding security vulnerabilities when uploading files, specifically, image files.
The following code is my controller code for the POST that uploads a new image file:
[HttpPost]
public virtual ActionResult StepImage(int CourseId, int StepOrder, HttpPostedFileBase file)
{
service.CourseId = CourseId;
service.StepOrder = StepOrder;
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var fileExtension = Path.GetExtension(fileName);
if ((fileExtension == ".jpg") || (fileExtension == ".gif") || (fileExtension == ".png"))
{
service.StoreImageFileName(fileName);
var path = Server.MapPath("~/[path to where images are uploaded]/" + service.CourseId + "/");
if(!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
file.SaveAs(path + fileName);
}
else
{
// Refactor notice : Validation for invalid file extension
}
}
else
{
// Refactor notice : Validation for no file chosen
}
return RedirectToAction(MVC.Admin.StepEditor.Actions.Edit(CourseId, StepOrder));
}
You can see from the above code that I check for the file extension and only allow .jpg, .gif and .png.
Questions
I tried storing the files under the App_Data folder, but this resulted in a 403 forbidden response when the Views try to display the images.
So I put them in ~/Images/...
Is there a security risk with this? Can someone upload an .exe file with a .jpg extension and get it to execute baddie code?
It has to be said that the risk is low, as only Tutors will have permissions to use the page that uploads the file, but you just need one disgruntled tutor... Or they give their login details to a student... or whatever.
Any other security risks in that code?
PS:
The basics are taken from Scott Hanselman's and Phil Haack's blog posts on the subject of uploading files using ASP.NET MVC 2 +:
Phil Haack post
Scott Hanselman post
You get a 403 response when you place the images in the App_Data folder because IIS prevents any browser from directly accessing files in App_Data.
Placing them in ~/Images/ works but depending on the security on that folder this could mean that anyone can list the contents of ~/Images/ and/or view the images. By default, IIS forbids listing the contents of any folder but viewing the images by anyone is allowed. So, if someones knows the filename of the images, they can view them.
A solution is to use URL based authentication. Only the tutors (or whoever needs to) will be able to see the images then.
If you want complete control over who sees what on what pages, you could still place the images in the App_Data folder and then stream them to who- or whatever needs them like this.
About uploading an .exe as a jpg, this is certainly possible. It will even work for any type of file.
However, you save the file to the disk and don't do anything yourself with it. That makes the risk very small that the .exe-as-jpg is executed on your server. Unless someones finds an exploit in .net code that forces .net to execute the jpg, this is very unlikely.
You also show the jpg to the user in your views. That carries once again the security risk that possibly the user's browser has an exploit that forces it to execute the .exe-as-jpg on the user's computer. However, I think that is still very unlikely to happen (but not impossible. It has been done before e.g. see this).
To prevent this, you would need code on your server side that checks every image to see if it really is an image. However, these (possibly non-existent) security risks are very small and even exploiting this risks would require someone who knows quite a lot of computers and programming. Personally, I wouldn't worry about this.
Absolute security is impossible (Well, short of never turning your computer on. If it doesn't do anything, nothing can go wrong after all). It all depends how much security you want and how much time & money you can invest.