Im trying to upload an image to an imagehost http://uploads.im/.
According to its very short API http://uploads.im/apidocs this is a way of doing that:
http://uploads.im/api?upload=http://www.google.com/images/srpr/nav_logo66.png
Note that in this example he is upploading an image from the internet and Im trying to upload a file from my computer.
Code:
public ActionResult SaveUploadedFile()
{
//Converts the image i want to upload to a bytearray
Image postData = img;
byte[] byteArray = imageToByteArray(postData);
//Is this adress not correct maybe? Is there a way to test?
WebRequest wrq = WebRequest.Create("http://uploads.im/api?upload=");
wrq.Method = ("POST");
//Im thinking that here I need som code
//that specifys the file i want to upload (bytearray)
using (WebResponse wrs = wrq.GetResponse())
using (Stream stream = wrs.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
string json = reader.ReadToEnd();
tempJson = json;
}
}
Please have look! Thanks!
EDIT, new code:
string filepath = #"c:\Users\xxxx\Desktop\Bilder\images\blank.gif";
using (WebClient client = new WebClient())
{
client.UploadFile("http://uploads.im/api?upload", filepath);
}
I get the error: : The underlying connection closed
EDIT with try catch:
string filepath = #"c:\Users\xxxx\Desktop\sack.png";
using (WebClient client = new WebClient())
{
try
{
client.UploadFile("http://uploads.im/api?upload", filepath);
}
catch (Exception e)
{
throw new ApplicationException(e);
}
}
private void UploadImage(string filepath)
{
using(WebClient uploader = new WebClient())
{
try
{
uploader.UploadFile(new Uri("http://uploads.im/api?upload"), filepath);
}
catch(Exception ex)
{
MessageBox.Show("An error occured :(\r\n" + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
I'm using http://uploads.im/api?upload as the Endpoint, because, as read in the docs, it will be treated as REQUEST and will automatically detect the upload of an image.
However, I tried this code myself and get disconnected every-time without any meaningful response, just The remote host unexpectedly closed the connection. According to the docs you should get a Bad request when something is wrong. I contacted the support and hope they can tell me more about it. (Edit: They did not)
Related
The front end seems to post fine and my routing seems to be working as my API seems to get the request and the filename is valid. However, when I attempt await request.Content.ReadAsStreamAsync(); it doesn't seem to read anything and I get a
Data at the root level is invalid. Line 1, position 1.
exception when de-serializing...
Been at this for awhile trying the different solutions available with no success.. please help.
Things I've tried:
Different content-types
Different webclient methods to upload (uploadstring, uploadfile, uploaddata)
Using WebRequest instead of webclient (I will consistently get an unsupported media type message as a response)
My code:
public string CreateJob()
{
string test = "";
string sURL = "http://" + _domain + _apiRoot + "CreateJob/OrderXML";
try
{
var ms = new MemoryStream();
using (FileStream src = System.IO.File.Open(#"C:\XML\PageDNAOrderXML.txt", FileMode.Open))
{
src.CopyTo(ms);
}
using (WebClient wc = new WebClient())
{
wc.Headers[HttpRequestHeader.ContentType] = "text/xml";
wc.Headers[HttpRequestHeader.AcceptEncoding] = "Encoding.UTF8";
//wc.Headers[HttpRequestHeader.ContentLength] = ms.Length.ToString();
wc.UploadString(sURL, ms.ToString());
}
}
catch (Exception ex)
{
test = ex.Message;
}
return test;
}
RESTful API
[System.Web.Http.HttpPost]
public async void CreateJob(string filename)
{
string success = "false";
try
{
//XDocument doc = XDocument.Load
XmlSerializer xmls = new XmlSerializer(typeof(PdnaXmlParse));
Stream reqStream = await Request.Content.ReadAsStreamAsync();
PdnaXmlParse res = (PdnaXmlParse)xmls.Deserialize(new XmlTextReader(reqStream));
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
I'm trying to get Http headers of a PDF viewer page, for can get the pdf file and read it. I'm using the following lines of code:
using (WebClient client = new WebClient()){
client.OpenRead(driver.Url);
string header_contentDisposition = client.ResponseHeaders["content-disposition"];
string filename = new ContentDisposition(header_contentDisposition).FileName;
}
But the server is not finding the source, I'm trying this too:
var disposition= System.Web.HttpContext.Current.Request.Headers["Content-Disposition"];
But Current is null. Any advises or links for understand better http headers, please. Thanks in advance.
You can get the file by other way using the webdriver in C#:
public string DownloadFile(string url, string filename)
{
var dirToSave = "C:/Directory/Test";
if (!Directory.Exists(dirToSave))
Directory.CreateDirectory(dirToSave);
var localPath = String.Format("{0}\\{1}", dirToSave, filename);
var client = new WebClient();
client.Headers[HttpRequestHeader.Cookie] = CookieString();
try
{ client.DownloadFile(GetAbsoluteUrl(url), localPath); }
catch (Exception ex)
{ Assert.Fail("Error to download the file: " + ex); }
return localPath;
}
I am trying to download a file from a MOXA UC8410 over FTP. My code is not working. Here is my code:
void download2()
{
Uri serverUri = new Uri("ftp://169.254.1.1/CFDisk/PCPACM/pcpacm.ini");
// The serverUri parameter should start with the ftp:// scheme.
if (serverUri.Scheme != Uri.UriSchemeFtp)
{
}
// Get the object used to communicate with the server.
WebClient request = new WebClient();
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential("admin", "admin");
try
{
byte[] newFileData = request.DownloadData(serverUri.ToString());
string fileString = System.Text.Encoding.UTF8.GetString(newFileData);
//Console.WriteLine(fileString);
}
catch (WebException e)
{
// Console.WriteLine(e.ToString());
MessageBox.Show(e.Response + e.Message);
}
}
I have also tried this :
void download()
{
try
{
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://169.254.1.1:21/CFDisk/PCPACM/pcpacm.ini"));
// using admin as the username and admin as the passward.
request.Credentials = new NetworkCredential("admin", "admin");
//request.KeepAlive = false;
request.Method = WebRequestMethods.Ftp.DownloadFile;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
processingfile(reader);
responseStream.Close();
reader.Close();
}
catch (Exception e2)
{
MessageBox.Show("Not connected" , e2.Message);
}
}
The code get to
Stream responseStream = response.GetResponseStream();
and it just stops, it never goes to the next line.
output says:
The thread 0x175c has exited with code 259 (0x103).
The thread 0x212c has exited with code 259 (0x103).
which does not help.
I can ftp to the MOXA UC8410 using the command prompt and I can download the file using FileZilla but not using my code. There is no firewall on the Moxa UC8410, so something most be wrong with my code.
UpDate:
UpDATE It is working !!!
but only if I go to local Area Connection Properties and change Internet Protocol Version 4(tcp/IPv4) to
use the following IP address:
IP address: 169.254.1.5
Subnet mask: 225.225.0.0
does anyone know why? and is there a way I can fix it where I do not have to do that ?
Why do I have to put them on the same sub domain ?
Since I cannot comment yet, I'll put my questions here:
1) When you log in using FileZilla, are you starting in the directory where CFDisk lies?
2) Are you using plain-text FTP? When using FTP over TLS, the approach is slightly different.
3) Does it throw an Exception? If so, please also give us more details about that.
Also, WebResponse, Stream and StreamReader are disposable.
I created (and tested on one of my remote servers) this little Windows Form application. It seems to work fine here. Give it a look.
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;
namespace FTPTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string localPath = #"C:\Temp\navigazione-privata.pdf";
string ftpIPAddress = "xxx.xxx.xxx.xxx";
string remoteFilepath = "/userdownloads/navigazione-privata.pdf";
string ftpPath = "ftp://" + ftpIPAddress + remoteFilepath;
using (WebClient request = new WebClient())
{
request.Credentials = new NetworkCredential("username", "password");
byte[] fileData = request.DownloadData(ftpPath);
using (FileStream file = File.Create(localPath))
{
file.Write(fileData, 0, fileData.Length);
file.Close();
}
MessageBox.Show("Requested file downloaded");
}
}
}
}
Im trying to download the source code for this webpage for a school project using c#.
this is the page im trying to get:
http://www.epicurious.com/tools/fooddictionary/entry?id=1650
I have tried code such as
HttpWebRequest request = (HttpWebRequest)
WebRequest.Create("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
and by using
WebClient client = new WebClient();
string value = client.DownloadString("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
and neither methods are getting me the page source. Any help would be appreciated.
using HttpWebRequest.Create
try
{
WebRequest req = HttpWebRequest.Create("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
req.Method = "GET";
string source;
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
source = reader.ReadToEnd();
}
}
catch (Exception ex)
{
//Log the exception
MessageBox.Show(ex.ToString());
}
Using DownloadString
WebClient client = new WebClient();
string reply = client.DownloadString("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
Above methods are working fine for me. Check the exception if any..
How about this...
string sourceCode = "";
Uri site = new Uri("http://www.epicurious.com/tools/fooddictionary/entry?id=1650");
WebRequest request = WebRequest.Create(site);
using(StreamReader reader = new StreamReader(request.GetResponse().GetResponseStream(), Encoding.ASCII)){
sourceCode = reader.ReadToEnd();
}
The "using" statement will close your streams for you. NOTE: Calling close on a stream will also call class on any streams it is using, this is why you only need the single using statement
I try download file from server with FileWebRequest. But I get error:
Method on download is here:
public string HttpFileGetReq(Uri uri, int reqTimeout, Encoding encoding)
{
try
{
string stringResponse;
var req = (FileWebRequest)WebRequest.Create(uri);
req.Timeout = reqTimeout;
req.Method = WebRequestMethods.File.DownloadFile;
var res = (FileWebResponse)req.GetResponse();
//using (var receiveStream = res.GetResponseStream())
//using (var readStream = new StreamReader(receiveStream,encoding))
//{
// stringResponse = readStream.ReadToEnd();
//}
return stringResponse="0K";
}
catch (WebException webException)
{
throw webException;
}
}
Usage is here:
public dynamic LoadRoomMsg(IAccount account, string roomId)
{
try
{
string uri = string.Format("http://www-pokec.azet.sk/_s/chat/nacitajPrispevky.php?{0}&lok={1}&lastMsg=0&pub=0&prv=0&r=1295633087203&changeroom=1" , account.SessionId, roomId);
var htmlStringResult = HttpFileGetReq(new Uri(uri), ReqTimeout, EncodingType);
//var htmlStringResult = _httpReq.HttpGetReq(new Uri(string.Format("{0}{1}?{2}&lok=", PokecUrl.RoomMsg,account.SessionId,roomId)),
// ReqTimeout, account.Cookies, EncodingType);
if (!string.IsNullOrEmpty(htmlStringResult))
{
return true;
}
return false;
}
catch (Exception exception)
{
throw exception;
}
}
URL on file is here.
I would like read this file to string variable, that’s all. If anyone have some time and can help me I would be very glad to him.
Your URL (http://...) will produce a HttpWebRequest. You can check with the debugger.
Form MSDN:
The FileWebRequest class implements
the WebRequest abstract base class for
Uniform Resource Identifiers (URIs)
that use the file:// scheme to request
local files.
Note the file:// and local files in there.
Tip: Just use the WebClient class.
Rather than implement your own web streams allow the .NET framework to do it all for you with WebClient, for example:
string uri = string.Format(
"http://www-pokec.azet.sk/_s/chat/nacitajPrispevky.php?{0}&lok={1}&lastMsg=0&pub=0&prv=0&r=1295633087203&changeroom=1",
account.SessionId,
roomId);
System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString(uri);
...parse the webdata response here...
Looking at the response from the URL you posted:
{"reason":0}
parsing that should be a simple task with a little string manipulation.
Change FileWebRequest and FileWebResponse to HttpWebRequest and HttpWebResponse.
It doesn't matter that what you're downloading may be a file; as far as the .NET Framework is concerned, you're just retrieving a page from a website.
FileWebRequest is for file:// protocols. Since you're using an http:// url, you want to use HttpWebRequest.
public string HttpFileGetReq(Uri uri, int reqTimeout, Encoding encoding)
{
string stringResponse;
var req = (HttpWebRequest)WebRequest.Create(uri);
req.Timeout = reqTimeout;
var res = (HttpWebResponse)req.GetResponse();
using (var receiveStream = res.GetResponseStream())
{
using (var readStream = new StreamReader(receiveStream,encoding))
{
return readStream.ReadToEnd();
}
}
}