I have url that point to image for example :
http://cg009.k12.sd.us/images/smilefacemoving.gif
instead of user will insert file i want to bind this file(image) to the c# fileupload control .
so the fileupload object will hold this file(image).
Just have a Textbox on your page to let them enter a URL and then do this when the form is submitted...
string url = YOUR_TEXTBOX.Text();
Uri uri;
try {
uri = new Uri(url);
}
catch (UriFormatException ex) {
// Error
throw ex;
}
byte[] file;
using (System.Net.WebClient client = new System.Net.WebClient()) {
file = client.DownloadData(uri);
}
// now you have the file
Watch out for uploaded viruses :)
I'm honestly not sure what you're asking. Are you asking how you can upload a file referenced via a URL to your own server utilizing the fileupload control?
Related
I am using "webclient" to download and save a file by url in windows application.
here is my code:
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Cookie, cc);
wc.DownloadFile(new Uri(e.Url.ToString()), targetPath);
this is working fine local system.(downloading the file and saved to target path automatically with out showing any popup).
But when i am trying to execute the .exe in server its showing save/open popup.
Is there any modifications require to download a file in server settings.
Please help me to download the file with out showing popup in server too.
thanks in advance..
Finally i got the solution for this issue..
herw the code:
WebClient wc = new WebClient();
wc.Headers.Add(HttpRequestHeader.Cookie, cc);
using (Stream data = wc.OpenRead(new Uri(e.Url.ToString())))
{
using (Stream targetfile = File.Create(targetPath))
{
data.CopyTo(targetfile);
}
}
here i just replaced the code
wc.DownloadFile(new Uri(e.Url.ToString()), targetPath);
with the blow lines:
using (Stream data = wc.OpenRead(new Uri(e.Url.ToString())))
{
using (Stream targetfile = File.Create(targetPath))
{
data.CopyTo(targetfile);
}
}
Now its working fine..
Thanks all for ur response..
I am uploading a file with C# code on php server. But facing some issues.
First I was using a WebClient Object to upload file by calling UploadFile() method, and uploading string to by calling UploadString() method by following code:
String StoreID = "First Store";
WebClient Client = new WebClient();
String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID);
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg");
s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length);
Issue is that I am requesting two times so string and file is not being send at same time. I am receiving either String or File. But I need both at same time. I don't want to use UploadData() becuase it will use byte codes and I have know I idea how to extract it in php.
Let that string is folder name, i have to send string and file, so that file could save at specified folder at php server.
I studied there may be a solution with WebRequest and WebResponse object. But dont know how to send request using WebResponse by C# and get it at PHP.
Any Suggestions!!!!
Try this :
WebClient web = new WebClient();
try{
web.UploadFile("http://" + ip + "/test.php", StoreID);
}
catch(Exception e)
{
MessageBox.Show("Upload failed");
}
Now you can access the file from the PHP file.
<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
//create the folder
mkdir('C:/Users/ComputerName/Desktop/test');
//give permission to the folder
chmod('C:/Users/ComputerName/Desktop/test', 0777);
}
//check whether the file exists
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]);
}
?>
Also, you can download data from a PHP server and display it in a C# web browser by using the following codes :
WebClient web = new WebClient();
try{
byte[] response = web.DownloadData("http://" + ip +"/test.php");
webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
MessageBox.Show("Download failed");
}
You can create a webservice with php that accepts a file. Then publish that webservice, and add it to you c# references, then just call teh method from within your c# code that accepts the file, and vualá!
How to create SOAP with php link
i faced an issue with downloading file from website.
A user can fill in the textbox (example: hello.html) and then click on a button to download the html file. Now my issue is: even the file "hello.html" is not exists, my code will tend to download it as well. There will be "index.html" file appears in folder. How do I write "if" statement so that I can tell the code not to download if the file is not exist?
My code:
if (FILE NOT EXIST ON THE WEBSITE)
{
//MessageBox.Show("There is no such file on the website. Please check your spelling.");
}
else
{
client.DownloadFile("http://example.com/" + txtbox.Text.ToUpper().ToString(),
sourceDir + txtbox.Text.ToUpper().ToString() + ".html");
}
Thank you so much.
System.IO.File.Exists(fpath) returns false in Chrome and Firefox
if (File.Exists(fileLocation))
{
// Download File!
}
That problem is specific for uploading but its the same concept.
OR:
Taken Directly from: http://www.dotnetthoughts.net/how-to-check-remote-file-exists-using-c/
Add this method to your class.
private bool RemoteFileExists(string url)
{
try
{
//Creating the HttpWebRequest
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD";
//Getting the Web Response.
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//Returns TURE if the Status code == 200
return (response.StatusCode == HttpStatusCode.OK);
}
catch
{
//Any exception will returns false.
return false;
}
}
Then when you want to check if a file exists at a url use this:
if (RemoteFileExists("http://blog.stackoverflow.com/wp-content/uploads/stackoverflow-logo-300.png")
{
//File Exists
}
else
{
//File does not Exist
}
Hi and thanks for looking!
Background
I am using the Rotativa pdf tool to read a view (html) into a PDF. It works great, but it does not natively offer a way to save the PDF to a file system. Rather, it only returns the file to the user's browser as a result of the action.
Here is what that code looks like:
public ActionResult PrintQuote(FormCollection fc)
{
int revisionId = Int32.Parse(Request.QueryString["RevisionId"]);
var pdf = new ActionAsPdf(
"Quote",
new { revisionId = revisionId })
{
FileName = "Quote--" + revisionId.ToString() + ".pdf",
PageSize = Rotativa.Options.Size.Letter
};
return pdf;
}
This code is calling up another actionresult ("Quote"), converting it's view to a PDF, and then returning the PDF as a file download to the user.
Question
How do I intercept the file stream and save the PDF to my file system. It is perfect that the PDF is sent to the user, but my client also wants the PDF saved to the file system simultaneously.
Any ideas?
Thanks!
Matt
I have the same problem, here's my solution:
You need to basically make an HTTP request to your own URL and save the output as a binary file. Simple, no overload, helper classes, and bloated code.
You'll need this method:
// Returns the results of fetching the requested HTML page.
public static void SaveHttpResponseAsFile(string RequestUrl, string FilePath)
{
try
{
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(RequestUrl);
httpRequest.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";
httpRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
HttpWebResponse response = null;
try
{
response = (HttpWebResponse)httpRequest.GetResponse();
}
catch (System.Net.WebException ex)
{
if (ex.Status == WebExceptionStatus.ProtocolError)
response = (HttpWebResponse)ex.Response;
}
using (Stream responseStream = response.GetResponseStream())
{
Stream FinalStream = responseStream;
if (response.ContentEncoding.ToLower().Contains("gzip"))
FinalStream = new GZipStream(FinalStream, CompressionMode.Decompress);
else if (response.ContentEncoding.ToLower().Contains("deflate"))
FinalStream = new DeflateStream(FinalStream, CompressionMode.Decompress);
using (var fileStream = System.IO.File.Create(FilePath))
{
FinalStream.CopyTo(fileStream);
}
response.Close();
FinalStream.Close();
}
}
catch
{ }
}
Then inside your controller, you call it like this:
SaveHttpResponseAsFile("http://localhost:52515/Management/ViewPDFInvoice/" + ID.ToString(), "C:\\temp\\test.pdf");
And voilĂ ! The file is there on your file system and you can double click and open the PDF, or email it to your users, or whatever you need.
return new Rotativa.ActionAsPdf("ConvertIntoPdf")
{
FileName = "Test.pdf", PageSize = Rotativa.Options.Size.Letter
};
Take a look at the MVC pipeline diagram here:
http://www.simple-talk.com/content/file.ashx?file=6068
The method OnResultExecuted() is called after the ActionResult is rendered.
You can override this method or use an ActionFilter to apply and OnResultExecuted interceptor using an attribute.
Edit:
At the end of this forum thread you will find a reply which gives an example of an ActionFilter which reads (and changes) the response stream of an action. You can then copy the stream to a file, in addition to returning it to your client.
I successfully used Aaron's 'SaveHttpResponseAsFile' method, but I had to alter it, as the currently logged in user's credentials weren't applied (and so it was forwarding to MVC4's login url).
public static void SaveHttpResponseAsFile(System.Web.HttpRequestBase requestBase, string requestUrl, string saveFilePath)
{
try
{
*snip*
httpRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
httpRequest.Headers.Add(HttpRequestHeader.Cookie, requestBase.Headers["Cookie"]);
*snip*</pre></code>
Then in your calling Controller method, simply add 'Request' into the SaveHttpResponseAsFile call.
You can also do it using Rotativa, which is actually quite easy.
Using Rotativa;
...
byte[] pdfByteArray = Rotativa.WkhtmltopdfDriver.ConvertHtml( "Rotativa", "-q", stringHtmlResult );
File.WriteAllBytes( outputPath, pdfByteArray );
I'm using this in a winforms app, to generate and save the PDFs from Razor Views we also use in our web apps.
I was able to get Eric Brown - Cal 's solution to work, but I needed a small tweak to prevent an error I was getting about the directory not being found.
(Also, looking at the Rotativa code, it looks like the -q switch is already being passed by default, so that might not be necessary, but I didn't change it.)
var bytes = Rotativa.WkhtmltopdfDriver.ConvertHtml(Server.MapPath(#"/Rotativa"), "-q", html);
I know how to save an image to a folder using the fileupload control with the saveas method. But I to take an image from the image control and save it to a file without using the fileupload control n save it in folder.
string filepath = img1.ImageUrl;
using (WebClient client = new WebClient())
{
client.DownloadFile(filepath,Server.MapPath("~/Image/apple.jpg"));
}
Do you know image path? you can get image path from image control and then download image in code:
Download image from the site in .NET/C#
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
First Get the Url of Image and then using webclient you can save file in folder
string filepath = img1.ImageUrl;
using (WebClient client = new WebClient())
{
client.DownloadFile(filepath,Server.MapPath("~/Image/apple.jpg"));
}
This will save image in Image Folder with ImageName apple...