How to download a jpg from web to project folder in MVC3? - asp.net-mvc-3

Hello everyone I would like to ask How can I download .jpg file from web to my project's folder which I have created "uploads" ?
I'm trying to downlaod youtube thumbnail image to my" uploads" folder.
My controller:
var fileName = Path.GetFileName(http://img.youtube.com/vi/RUgd_GDPhYk/1.jpg);
var path = Path.Combine(Server.MapPath("~/uploads/"), fileName);
file.SaveAs(path);

Take a look at System.Net.WebClient, a .NET class which allows you to make requests for resources via HTTP.
http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.100).aspx
Checked example provided.
var client = new System.Net.WebClient();
var uri = "http://img.youtube.com/vi/RUgd_GDPhYk/1.jpg";
// Here, we're just using the same filename as the resource we're after.
// You may wish to change this to include extra stuff because you'll
// inevitably run into a naming clash - especially with stuff like 1.jpg
var targetFilename = Path.GetFileName(uri);
client.DownloadFile(uri,
Path.Combine(Server.MapPath("~/uploads"), targetFilename));

Related

Play Framework: Handling dynamic created files (images) in PRODUCTION mode

I'm trying to allow users to upload photos to the server and then view them (all users can view all photos) in production (NOT development). While in development mode everything is simple - I can upload the files to the public folder and then read then from there, in production mode I don't have access to the public folder anymore (as this approach is for static accesses and not dynamic).
So, I have 2 issues:
Upload: currently I can't understand how to save the uploaded photos to a specific folder, without using an absolute path to the location where I want the photos to be saved.
Here is the code for upload (similarly to this guide - https://www.playframework.com/documentation/2.4.x/ScalaFileUpload):
def uploadPhoto = Action(parse.multipartFormData) { request =>
import play.api.mvc.MultipartFormData
import play.api.libs.Files.TemporaryFile
import java.io.File
import java.nio.file.Path
import java.nio.file.Paths
try {
val multipartForm: MultipartFormData[TemporaryFile] = request.body
val pathDev: Path = Paths.get("./public/img");
val pathProduction: Path = Paths.get("/...<[full path]>.../public/img");
val imgPath =
if (Files.exists(pathDev)) { pathDev.toString() }
else { pathProduction.toString() }
val newFile = img.get.ref.moveTo(new File(s"$imgPath/$imgName"))
// [HERE I save the path to my DB]
Ok(Json.obj("imgName" -> imgName))
} catch {
case e: Exception =>
BadRequest("unknown error")
}
}
It is unclear to me how to serve the uploaded images back to users that want to see them.
I want to dynamically change the scr in the img html tag to show the relevant image, like so: $("#img").attr("src",'assets/img/1.jpg');
But as the public folder is not available, the images are "not there" (at least until I will "stage" the project and re-run it - https://www.playframework.com/documentation/2.4.x/Assets).
I tried the following approach (https://www.playframework.com/documentation/2.4.x/ScalaStream):
I have added the following line to my conf/routes file:
GET /img/:filename controllers.MyController.getPhoto(filename)
and defined the following function in the controller:
def getPhoto(filename: String) = Action {
Ok.sendFile(new java.io.File("./img/" + filename))
}
But the browser is downloading the file instead of showing it...
These are related:
Handling dynamic created files in play 2
How to serve uploaded files in Play!2 using Scala?
Any assistance will be very appropriated.
Here's how I fix this
ISSUE 1
For upload file path, in play you can define configurations in conf/application.conf file, and you can use different file for production mode, using -Dconfig.file=/path/to/the/file.
So I defined an attribuite called myapp.image.base, in debug mode just set it to "", and in production mode (I created a file called conf/application.prod.conf) , I put an absolute path to it.
So in my code, I always use the following command for file path (it's in Java, but you should find a similar way in Scala for reading configuration)
Play.application().configuration().getString("myapp.image.base")+"img"
ISSUE 2
For serving image
You need to create a router.
First in your routes file, add something like this:
GET /user/images/:name controllers.Application.imageAt(name:String)
And write a simple file reader in action imageAt which return the file in stream. Again my sample is in Java but you should archive the same using Scala
File imageFile = new File(ReportFileHelper.getImagePath());
if (imageFile.exists()) {
//resource type such as image+png, image+jpg
String resourceType = "image+"+imageName.substring(imageName.length()-3);
return ok(new FileInputStream(imageFile)).as(resourceType);
} else {
return notFound(imageFile.getAbsoluteFile());
}
After that, the images is reachable from url /user/images/
Play reads files off the classpath (which includes the assets directory). On the JVM, the classpath is immutable—once started, files added to folders on the classpath will not actually be added to the classpath.
This works in development mode because Play reloads the classpath whenever it detects a change. That same hot-reloading is not enabled in production (for good reason).

trouble accessing files loaded into project

I've added a bunch of files to my swift project folder like so:
I need to access these files at a certain point in the project for two purposes:
Use the name of each file to populate Categories (ie. Age, Alone, Amazing...)
Access the data within the files to populate each Category items page
I've implemented this code in the viewDidLoad of my class to access and iterate through the files
//get categories
let fileManager = NSFileManager.defaultManager()
let directoryPath = NSHomeDirectory() + "/Categories"
let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!
while let element = enumerator.nextObject() as? String {
println(String(element))
}
This does not work and produces the error fatal error: unexpectedly found nil while unwrapping an Optional value on the line let enumerator:NSDirectoryEnumerator = fileManager.enumeratorAtPath(directoryPath)!. I suspect (and correct me if I'm wrong), that it is accessing the applications internal file structure and as a result cannot find the files specified. As I am new to IOS development, my general understanding of how this works is nebulous at best.
So How exactly do I access files I've added the project in the way I've shown in the image, so as to iterate through and get the data I'm looking for
EDIT
So I've changed the structure to make the Categories folder an actual folder like so:
I'm currently trying to use NSBundle to access the application route, however I am not sure how to do that. Any guidance would be appreciated.
The problem is that xcode's project navigator folders are not actual folders in the disk. So this:
let directoryPath = NSHomeDirectory() + "/Categories"
does not exist in your hdd. If you want this folder you have to navigate to your projects folder on your hdd, create it manually and add the files you want in it.
You can refer to a file and read it like this:
let htmFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "html")
let htmlString = NSString(contentsOfFile: htmFile!, encoding: NSUTF8StringEncoding, error: nil)
for json you can get a dictionary with
let jsonFile = NSBundle.mainBundle().pathForResource("aboutText", ofType: "json")
let dict = NSDictionary(contentsOfFile: jsonFile)

Add download to Firefox via Firefox extension

This is my first Firefox extension which I'm developing with addon-builder [builder.addons.mozilla.org/] .
My question is simple but after trying many things, for many days, I'm unable to get results.
I want to know: How to add a file download to Firefox downloader??
I've a url like: http:// example.com/file.zip and a file location like: D:\myFolder.
I want to add this download via my firefox extension.
The things which I've searched are:
https://developer.mozilla.org/en-US/docs/XPCOM_Interface_Reference/nsIWebBrowserPersist#saveURI%28%29
https://developer.mozilla.org/en-US/docs/Code_snippets/Downloading_Files
Components.utils.import("resource://gre/modules/PrivateBrowsingUtils.jsm");
const WebBrowserPersist = Components.Constructor("#mozilla.org/embedding/browser/nsWebBrowserPersist;1",
"nsIWebBrowserPersist");
var persist = WebBrowserPersist();
var targetFile = Services.dirsvc.get("Desk", Ci.nsIFile);
targetFile.append("file.bin");
// Obtain the privacy context of the browser window that the URL
// we are downloading comes from. If, and only if, the URL is not
// related to a window, null should be used instead.
var privacy = PrivateBrowsingUtils.privacyContextFromWindow(urlSourceWindow);
persist.persistFlags = persist.PERSIST_FLAGS_FROM_CACHE
| persist.PERSIST_FLAGS_REPLACE_EXISTING_FILES;
persist.saveURI(uriToSave, null, null, null, "", targetFile, privacy);
Can you just gimme a start from where I should get the easiest possible download function.
Components.utils.import("resource://gre/modules/Services.jsm");
var {downloads}=Services;
downloads.addDownload(/*parameters*/); //see documentation for parameters.
Documentation for addDownload: nsIDownloadManager#addDownload()
Documentation and directory for the wide range of services provided by Services.jsm: Services.jsm

path from isolated storage windows phone

hi i have a simple question how i can find the path of a file which had been already saved in the isolated storage
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(App.filePath, FileMode.Create, store))
{
byte[] buffer = new byte[1024];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
stream.Close();
}
now i would read this file
i need this path to use it as a parameter of method
Epub epub =new Epub([file path])
any help will be greatly appreciated
If a file is in IsolatedStorage you either put there yourself or it's the one created by the system to store settings.
If you put it there you must have had the path at some point previously. You just need to track the file names (and paths) you're using.
You should not try and access the settings file directly.
Try this
using (var AppStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] filenames=AppStorage.getFileNames();
//choose the filename you want or
//enumerate directories and read file names in each directory
string[] directories=AppStorage.getDirectories();
}
For each directory you have to add the filepath upto that directory just like in any windows file browsing.
Hope it helps.Post your further queries.
There is no need for you to get the path to the file if you are the one who put the file in the isolated storage. The entire guide to how properly read and write files to the app isostore is available here, and this should be your starting point.
The entire reading routine is limited to this:
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("myFile.txt", FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fileStream))
{
Console.WriteLine("Reading contents:");
Console.WriteLine(reader.ReadToEnd());
}
}
Where myIsolatedStorage is equal to IsolatedStorageFile.GetUserStoreForApplication() (akak your local app storage box).
No need for Reflection, as you showed in the comments. The can be relative to a folder, when you're attempting to read, so something like /MyFolder/myFile.txt will work as well, given that the folder exists.
Your problem is this - pushing the relative path in the isostore to the Epub class, which probably does not read directly from the isostore and uses a full path instead. The nature of the Windows Phone OS is such that it won't let a third-party application without proper permissions to access content directly through a full path reference. So you need to figure out a way to pass binary content to the class instead of a path.

How to upload image in Windows Azure platform: best approach

Ihave a register form with an Image Upload and it doesn't work when I upload my package application in my Windows Azure server.
The image address in the server looks like this:
F:\sitesroot\0\Uploads\Users\9259826_2121813246965_1294840438_2490950_6619588_n.jpg
If I had this image url like this, with it's relative path:
http://dealma.cloudapp.net/Uploads/Users/9259826_2121813246965_1294840438_2490950_6619588_n.jpg
I would already solve the problem.
The current code I'm using to upload is this:
if (userImg != null && userImg.ContentLength > 0)
{
try
{
var fileName = Url.Encode(userImg.FileName);
//no overwrite files
var pathToCheck = Server.MapPath("~/Uploads/Users/" + fileName);
var savePath = Server.MapPath("~/Uploads/Users/");
var tempfileName = fileName;
int counter = 2;
while (System.IO.File.Exists(pathToCheck))
{
tempfileName = counter.ToString() + fileName;
pathToCheck = savePath + tempfileName;
counter++;
}
fileName = tempfileName;
var finalImg = Path.Combine(savePath, fileName);
userImg.SaveAs(finalImg);
//Img name
userSet.Picture = finalImg;
userSet.Thumbnail = finalImg;
}
catch (Exception ex)
{
Response.Write("Não foi possível fazer upload do arquivo: " + ex.Message);
}
}
Does anyone knows how to solve this problem?
As corvus stated, you are writing to "local storage" which is volatile and not shared across multiple instances of your virtual machine.
Blob storage lets you store arbitrary files, images, etc. Each item gets stored in its own blob. You also have the notion of a "container" - think of it as a top-level directory folder. There are no nested containers, but you can emulate them with path characters in the name (skip this for now, as you need a quick solution).
If you download the Windows Azure Platform Training Kit and look at the lab "Introduction to Cloud Services", it shows a Guestbook application, where photos are uploaded to blob storage. You will see how to set up a storage account, as well as writing the code to push your file to a blob instead of the local file system. Here's a snippet from the sample:
Initialize blob client, and set up container to store your files:
var storageAccount =
CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
// create blob container for images
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("uploads");
container.CreateIfNotExist();
Now, in your upload handler, you'd write to a blob instead of local file system:
string uniqueBlobName = string.Format("uploads/image_{0}{1}",
Guid.NewGuid(), Path.GetExtension(UserImg.FileName));
CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = UserImg.PostedFile.ContentType;
// note: there are several blob upload methods -
// choose the best one that fits your app
blob.UploadFromStream(UserImg.FileContent);
You'll see the full working sample once you download the Platform Training Kit.
You are trying to save the image to the virtual machine where web role handling your request resides.
Probably there is more than one web role instance in your application. So, the file gets saved on one machine, but next request is served by another web role and virtual machine that doesn't have this file.
So, good idea is to save all data that needs to be accessible from any web role, to blobs. If you have some static data, you can put this data into package with your web role. All other data should reside in blobs.
If you don't want to modify the code of your application, you can map a part of blob storage as another hard drive to every instance of your web role. In this case, you just need to write received data to this mapped disk. The results will be accessible from any web role.

Resources