I am trying to write a proxy which reads an image from one server and returns it to the HttpContext supplied, but I am just getting character stream back.
I am trying the following:
WebRequest req = WebRequest.Create(image);
WebResponse resp = req.GetResponse();
Stream stream = resp.GetResponseStream();
StreamReader sr = new StreamReader(stream);
StreamWriter sw = new StreamWriter (context.Response.OutputStream);
sw.Write (sr.ReadToEnd());
But as I mentioned earlier, this is just responding with text.
How do I tell it that it is an image?
Edit: I am accessing this from within a web page in the source attribute of an img tag. Setting the content type to application/octet-stream prompts to save the file and setting it to image/jpeg just responds with the filename. What I want is the image to be returned and displayed by the calling page.
Since you are working with binary, you don't want to use StreamReader, which is a TextReader!
Now, assuming that you've set the content-type correctly, you should just use the response stream:
const int BUFFER_SIZE = 1024 * 1024;
var req = WebRequest.Create(imageUrl);
using (var resp = req.GetResponse())
{
using (var stream = resp.GetResponseStream())
{
var bytes = new byte[BUFFER_SIZE];
while (true)
{
var n = stream.Read(bytes, 0, BUFFER_SIZE);
if (n == 0)
{
break;
}
context.Response.OutputStream.Write(bytes, 0, n);
}
}
}
I guess you would need to check the ContentType returned by your WebResponse request.
if (resp.ContentType.StartsWith("image/"))
{
// Do your stuff
}
You're going to need to set the Content Type on your response. Here's a snippet of code that'll do it:
// specify that the response is a JPEG
// Also could use "image/GIF" or "image/PNG" depending on what you're
// getting from the server
Response.ContentType = "image/JPEG";
I use this in an application currently. Content URL is passed in as a query string value (the URL to the image).
try
{
if (ContentUrl != "")
{
string imgExtension = ContentUrl.Substring(ContentUrl.Length - 3, 3);
switch (imgExtension)
{
case "":
//image/bmp
Response.ContentType = "image/bmp";
break;
case "jpg":
//image/jpeg
Response.ContentType = "image/jpeg";
break;
case "gif":
//image/gif
Response.ContentType = "image/gif";
break;
default:
Response.ContentType = "image/jpeg";
break;
}
if (!ContentUrl.StartsWith("http"))
Response.BinaryWrite(new byte[] { 0 });
WebClient wc = new WebClient();
wc.Credentials = System.Net.CredentialCache.DefaultCredentials;
Byte[] result;
result = wc.DownloadData(ContentUrl);
Response.BinaryWrite(result);
}
}
catch (Exception ex)
{
Utility.WriteEventError(Utility.EVENTLOG_SOURCE, string.Format("ImageProxy Error... Url: {0}, Exception: {1}", ContentUrl, ex.ToString()));
}
finally
{
Response.End();
}
Related
I need to stream a file which will result in save as prompt in the browser.
The issue is, the directory that the file is located is virtually mapped, so I am unable to use Server.MapPath to determine it's actual location. The directory is not in the same location (or even phyical server on the live boxes) as the website.
I'd like something like the following, but that will allow me to pass a web URL, and not a server file path.
I may have to end up building my file path from a config base path, and then append on the rest of the path, but hopefully I can do it this way instead.
var filePath = Server.MapPath(DOCUMENT_PATH);
if (!File.Exists(filePath))
return;
var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();
You could use HttpWebRequest to get the file and stream it back to the client. This allows you to get the file with a url. An example of this that I found ( but can't remember where to give credit ) is
//Create a stream for the file
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest) HttpWebRequest.Create(url);
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse) fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Current.Response;
//Indicate the type of data being sent
resp.ContentType = MediaTypeNames.Application.Octet;
//Name the file
resp.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (resp.IsClientConnected)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.OutputStream.Write(buffer, 0, length);
// Flush the data
resp.Flush();
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
Download url to bytes and convert bytes into stream:
using (var client = new WebClient())
{
var content = client.DownloadData(url);
using (var stream = new MemoryStream(content))
{
...
}
}
I do this quite a bit and thought I could add a simpler answer. I set it up as a simple class here, but I run this every evening to collect financial data on companies I'm following.
class WebPage
{
public static string Get(string uri)
{
string results = "N/A";
try
{
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
StreamReader sr = new StreamReader(resp.GetResponseStream());
results = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{
results = ex.Message;
}
return results;
}
}
In this case I pass in a url and it returns the page as HTML. If you want to do something different with the stream instead you can easily change this.
You use it like this:
string page = WebPage.Get("http://finance.yahoo.com/q?s=yhoo");
2 years later, I used Dallas' answer, but I had to change the HttpWebRequest to FileWebRequest since I was linking to direct files. Not sure if this is the case everywhere, but I figured I'd add it. Also, I removed
var resp = Http.Current.Resonse
and just used Http.Current.Response in place wherever resp was referenced.
If you are looking for a .NET Core version of #Dallas's answer, use the below.
Stream stream = null;
//This controls how many bytes to read at a time and send to the client
int bytesToRead = 10000;
// Buffer to read bytes in chunk size specified above
byte[] buffer = new Byte[bytesToRead];
// The number of bytes read
try
{
//Create a WebRequest to get the file
HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(#"file url");
//Create a response for this request
HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();
if (fileReq.ContentLength > 0)
fileResp.ContentLength = fileReq.ContentLength;
//Get the Stream returned from the response
stream = fileResp.GetResponseStream();
// prepare the response to the client. resp is the client Response
var resp = HttpContext.Response;
//Indicate the type of data being sent
resp.ContentType = "application/octet-stream";
//Name the file
resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());
int length;
do
{
// Verify that the client is connected.
if (!HttpContext.RequestAborted.IsCancellationRequested)
{
// Read data into the buffer.
length = stream.Read(buffer, 0, bytesToRead);
// and write it out to the response's output stream
resp.Body.Write(buffer, 0, length);
//Clear the buffer
buffer = new Byte[bytesToRead];
}
else
{
// cancel the download if client has disconnected
length = -1;
}
} while (length > 0); //Repeat until no data is read
}
finally
{
if (stream != null)
{
//Close the input stream
stream.Close();
}
}
I would argue the simplest way to do so in .Net Core is:
using (MemoryStream ms = new MemoryStream())
using (HttpClient client = new HttpClient())
{
client.GetStreamAsync(url).Result.CopyTo(ms);
// use ms in what you want
}
}
now you have the file downloaded as stream inside ms.
You could try using the DirectoryEntry class with the IIS path prefix:
using(DirectoryEntry de = new DirectoryEntry("IIS://Localhost/w3svc/1/root" + DOCUMENT_PATH))
{
filePath = de.Properties["Path"].Value;
}
if (!File.Exists(filePath))
return;
var fileInfo = new System.IO.FileInfo(filePath);
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", String.Format("attachment;filename=\"{0}\"", filePath));
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.WriteFile(filePath);
Response.End();
The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).
The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.
So what was missing was:
Response.End();
See also:
Trying to stream a PDF file with asp.net is producing a "damaged file"
I'm trying create a small http proxy service. This is not working so well. It is able to serve HTML okayish, however it chokes up on images. That is, some images.
Sending in a url through my proxy yields 19.4 kb in the response (according to firebug)
Visiting that url directly also yields 19.4 kb in the response, again according to firebug. The difference is, it doesn't show up when I put it through my proxy, but it does when I browse directly.
A completely different url works just fine. Does anyone have any idea?
private void DoProxy()
{
var http = listener.GetContext();
string url = http.Request.QueryString["url"];
WebRequest request = HttpWebRequest.Create(url);
WebResponse response = request.GetResponse();
http.Response.ContentType = response.ContentType;
byte[] content;
using (Stream responseStream = response.GetResponseStream())
content = ReadAll(responseStream);
http.Response.ContentLength64 = content.Length;
http.Response.OutputStream.Write(content, 0, content.Length);
http.Response.Close();
}
private byte[] ReadAll(Stream stream)
{
IList<byte> array = new List<byte>();
int b;
while ((b = stream.ReadByte()) != -1)
array.Add(Convert.ToByte(b));
return array.ToArray();
}
I would try and flush/close the OutputStream before you close the response.
Also as a second suggestion have a look at the HTTP traffic from the original site and then through your proxy site using an HTTP debugger like Fiddler - there must be a difference when using your proxy.
Also to make the ReadAll method more effective, in general I would avoid to load the full content into memory, because this will blow up on huge files - just stream them directly from the input stream to the output stream. If you still want to use byte arrays consider the following (untested but should work):
private byte[] ReadAll(Stream stream)
{
byte[] buffer = new byte[8192];
int bytesRead = 1;
List<byte> arrayList = new List<byte>();
while (bytesRead > 0)
{
bytesRead = stream.Read(buffer, 0, buffer.Length);
arrayList.AddRange(new ArraySegment<byte>(buffer, 0, bytesRead).Array);
}
return arrayList.ToArray();
}
You can try to replace
http.Response.Close();
with
http.Response.Flush();
http.Response.End();
A problem could be that you don't specify the MIME type of the response. Browsersthese days are very forgiving, but maybe there is a circumstance where the browser doesn't know how to handle whatever you are sticking through its throat.
I have written the most smallish file-based http server, presented here, which as far as I can remember can serve images without much problem.
Just separate the text response and image response, and write the outputs separately. I did like below and it worked for me.
static void Main(string[] args)
{
HttpListener server = new HttpListener();
server.Prefixes.Add("http://localhost:9020/");
server.Start();
Console.WriteLine("Listening...");
while (true)
{
try
{
HttpListenerContext context = server.GetContext();
HttpListenerResponse response = context.Response;
String localpath = context.Request.Url.LocalPath;
string page = Directory.GetCurrentDirectory() + localpath;
string msg = "";
bool imgtest = false;
if (localpath == "/")
page = "index.html";
Console.WriteLine(localpath);
if (!page.Contains("jpg") && !page.Contains("png"))//Separates image request
{
TextReader tr = new StreamReader(page);
msg = tr.ReadToEnd();
tr.Dispose();
}
else
{
byte[] output = File.ReadAllBytes(page);
response.ContentLength64 = output.Length;
Stream st1 = response.OutputStream;
st1.Write(output, 0, output.Length);
imgtest = true;
}
if (imgtest==false)
{
byte[] buffer = Encoding.UTF8.GetBytes(msg);
response.ContentLength64 = buffer.Length;
Stream st = response.OutputStream;
st.Write(buffer, 0, buffer.Length);
context.Response.Close();
}
}
catch (Exception ex)
{
Console.WriteLine("Error: "+ex);
Console.ReadKey();
}
}
I am trying to download images from the site. The code which I am using is working fine while the image is available. If the image it not available it is creating a problem. How to validate availability of the image?
Code:
Method 1:
WebRequest requestPic = WebRequest.Create(imageUrl);
WebResponse responsePic = requestPic.GetResponse();
Image webImage = Image.FromStream(responsePic.GetResponseStream()); // Error
webImage.Save("D:\\Images\\Book\\" + fileName + ".jpg");
Method 2:
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
bitmap = new Bitmap(stream); // Error : Parameter is not valid.
stream.Flush();
stream.Close();
client.dispose();
if (bitmap != null)
{
bitmap.Save("D:\\Images\\" + fileName + ".jpg");
}
Edit:
Stream has the following statements:
Length '((System.Net.ConnectStream)(str)).Length' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}
Position '((System.Net.ConnectStream)(str)).Position' threw an exception of type 'System.NotSupportedException' long {System.NotSupportedException}
ReadTimeout 300000 int
WriteTimeout 300000 int
There is no need to involve any image classes, you can simply call WebClient.DownloadFile:
string localFilename = #"c:\localpath\tofile.jpg";
using(WebClient client = new WebClient())
{
client.DownloadFile("http://www.example.com/image.jpg", localFilename);
}
Update
Since you will want to check whether the file exists and download the file if it does, it's better to do this within the same request. So here is a method that will do that:
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image",StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download oit
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
In brief, it makes a request for the file, verifies that the response code is one of OK, Moved or Redirect and also that the ContentType is an image. If those conditions are true, the file is downloaded.
I have used Fredrik's code above in a project with some slight modifications, thought I'd share:
private static bool DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response;
try
{
response = (HttpWebResponse)request.GetResponse();
}
catch (Exception)
{
return false;
}
// Check that the remote file was found. The ContentType
// check is performed since a request for a non-existent
// image file might be redirected to a 404-page, which would
// yield the StatusCode "OK", even though the image was not
// found.
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
// if the remote file was found, download it
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
return true;
}
else
return false;
}
Main changes are:
using a try/catch for the GetResponse() as I was running into an exception when the remote file returned 404
returning a boolean
Also possible to use DownloadData method
private byte[] GetImage(string iconPath)
{
using (WebClient client = new WebClient())
{
byte[] pic = client.DownloadData(iconPath);
//string checkPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) +#"\1.png";
//File.WriteAllBytes(checkPath, pic);
return pic;
}
}
private static void DownloadRemoteImageFile(string uri, string fileName)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
if ((response.StatusCode == HttpStatusCode.OK ||
response.StatusCode == HttpStatusCode.Moved ||
response.StatusCode == HttpStatusCode.Redirect) &&
response.ContentType.StartsWith("image", StringComparison.OrdinalIgnoreCase))
{
using (Stream inputStream = response.GetResponseStream())
using (Stream outputStream = File.OpenWrite(fileName))
{
byte[] buffer = new byte[4096];
int bytesRead;
do
{
bytesRead = inputStream.Read(buffer, 0, buffer.Length);
outputStream.Write(buffer, 0, bytesRead);
} while (bytesRead != 0);
}
}
}
The best practice to download an image from Server or from Website and store it locally.
WebClient client=new Webclient();
client.DownloadFile("WebSite URL","C:\\....image.jpg");
client.Dispose();
You can use this code
using (WebClient client = new WebClient()) {
Stream stream = client.OpenRead(imgUrl);
if (stream != null) {
Bitmap bitmap = new Bitmap(stream);
ImageFormat imageFormat = ImageFormat.Jpeg;
if (bitmap.RawFormat.Equals(ImageFormat.Png)) {
imageFormat = ImageFormat.Png;
}
else if (bitmap.RawFormat.Equals(ImageFormat.Bmp)) {
imageFormat = ImageFormat.Bmp;
}
else if (bitmap.RawFormat.Equals(ImageFormat.Gif)) {
imageFormat = ImageFormat.Gif;
}
else if (bitmap.RawFormat.Equals(ImageFormat.Tiff)) {
imageFormat = ImageFormat.Tiff;
}
bitmap.Save(fileName, imageFormat);
stream.Flush();
stream.Close();
client.Dispose();
}
}
Project available at: github
Here is the working code in Python (using cURL):
#!/usr/bin/python
import pycurl
c = pycurl.Curl()
values = [
("key", "YOUR_API_KEY"),
("image", (c.FORM_FILE, "file.png"))]
# OR: ("image", "http://example.com/example.jpg"))]
# OR: ("image", "BASE64_ENCODED_STRING"))]
c.setopt(c.URL, "http://imgur.com/api/upload.xml")
c.setopt(c.HTTPPOST, values)
c.perform()
c.close()
Here's what I have in C#:
public void UploadImage()
{
//I think this line is doing something wrong.
//byte[] x = File.ReadAllBytes(#"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\hotness2.jpg");
//If I do it like this, using a direct URL everything works fine.
string parameters = #"key=1b9189df79bf3f8dff2125c22834210903&image=http://static.reddit.com/reddit.com.header.png"; //Convert.ToBase64String(x);
WebRequest webRequest = WebRequest.Create(new Uri("http://imgur.com/api/upload"));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = "POST";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
Stream os = null;
try
{ // send the Post
webRequest.ContentLength = bytes.Length; //Count bytes to send
os = webRequest.GetRequestStream();
os.Write(bytes, 0, bytes.Length); //Send it
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Request error");
}
finally
{
if (os != null)
{
os.Close();
}
}
try
{ // get the response
WebResponse webResponse = webRequest.GetResponse();
StreamReader sr = new StreamReader(webResponse.GetResponseStream());
MessageBox.Show(sr.ReadToEnd().Trim());
}
catch (WebException ex)
{
MessageBox.Show(ex.Message, "HttpPost: Response error");
}
}
Now, the things I noticed is that when I changed my API key in the parameters string to "239231" or whatever number, the response I got was: "Invalid API key." So I think something must be working right.
I placed my correct API key and now I get a different response: "Invalid image format. Try uploading a JPEG image."
The service I'm using accepts almost every image format, so I am 100% certain the error is in the way I'm sending the file. Can anyone shed some light?
EDIT!!!
It turns out when I upload a JPG image I get that gray box thing. If I upload a big jpg image I don't get anything. For example: http://i.imgur.com/gFsUY.jpg
When I upload PNG's, the image uploaded doesn't even show.
I'm certain the issue is the encoding. What can I do?
EDIT 2!!!
Now I'm 100% certain that the problem lies in the first line of the method. The File.ReadAllBytes() must be doing something wrong. If I upload a URL file, every works peachy: http://imgur.com/sVH61.png
I wonder what encoding I should use. :S
Try this:
string file = #"C:\Users\Sergio\documents\visual studio 2010\Projects\WpfApplication1\WpfApplication1\Test\Avatar.png";
string parameters = #"key=1df918979bf3f8dff2125c22834210903&image=" +
Convert.ToBase64String(File.ReadAllBytes(file));
You should correctly form a multipart POST request. See an example here: Upload files with HTTPWebrequest (multipart/form-data)
Read image posted by in API
public IHttpActionResult UpdatePhysicianImage(HttpRequestMessage request)
{
try
{
var form = HttpContext.Current.Request.Form;
var model = JsonConvert.DeserializeObject<UserPic>(form["json"].ToString());
bool istoken = _appdevice.GettokenID(model.DeviceId);
if (!istoken)
{
statuscode = 0;
message = ErrorMessage.TockenNotvalid;
goto invalidtoken;
}
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
if (httpRequest.Files.Count > 0)
{
var docfiles = new List<string>();
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
// var filePath = uploadPath + postedFile.FileName;
// string fileUrl = Utility.AbsolutePath("~/Data/User/" + model.UserId.ToString());
string fileUrl = Utility.AbsolutePath("~/" + Utility.UserDataFolder(model.UserId, "Document"));
if (!Directory.Exists(fileUrl))
{
Directory.CreateDirectory(fileUrl);
Directory.CreateDirectory(fileUrl + "\\" + "Document");
Directory.CreateDirectory(fileUrl + "\\" + "License");
Directory.CreateDirectory(fileUrl + "\\" + "Profile");
}
string imageUrl = postedFile.FileName;
string naviPath = Utility.ProfileImagePath(model.UserId, imageUrl);
var path = Utility.AbsolutePath("~/" + naviPath);
postedFile.SaveAs(path);
docfiles.Add(path);
if (model.RoleId == 2)
{
var doctorEntity = _doctorProfile.GetNameVideoChat(model.UserId);
doctorEntity.ProfileImagePath = naviPath;
_doctorProfile.UpdateDoctorUpdProfile(doctorEntity);
}
else
{
var patientEntity = _PatientProfile.GetPatientByUserProfileId(model.UserId);
patientEntity.TumbImagePath = naviPath;
_PatientProfile.UpdatePatient(patientEntity);
}
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
}
else
{
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
catch (Exception e)
{
statuscode = 0;
message = "Error" + e.Message;
}
invalidtoken:
return Json(modeldata.GetData(statuscode, message));
}
Try changing :-
"application/x-www-form-urlencoded"
to
"multipart/form-data"
Try adding the content-type for the jpg into your multipart boundary.
See this uRL for examples (at the end)
http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2
Shot in the dark, but maybe create an instance of Image, save the file to a Stream and use that to read the bytes into an array then upload it.
As in:
Image i = System.Drawing.Image.FromFile("wut.jpg");
Stream stm = new Stream();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
System.Drawing.Imaging.EncoderParameters paramz = new System.Drawing.Imaging.EncoderParameters(1);
myEncoderParameter = new EncoderParameter(myEncoder, 100L);
paramz.Param[0] = myEncoderParameter;
i.Save(stm, System.Drawing.Imaging.ImageFormat.Jpeg, paramz);
/* I'm lazy: code for reading Stream into byte[] here */
I am working on a mobile application on .net. This is a windows mobile application. I am facing a problem in this application that I wanna upload an image/file to given url/server. Many upload classes is not using like Webclient, WebRequest, WebResponse. I used HttpWebRequest, That is not connecting with server. Please anyone can help me on how to upload the images on given url in windows mobile 6 in .net.
Thanks in advance.
Hey take a look at this code for uploading at Image Shack:
You can modify it to use with other web site by just using Fiddler to change the web requests
public class Uploader
{
public string UploadFileToImageShack(object oFileName)
{
try
{
string fileName = oFileName as string;
string contentType = null;
CookieContainer cookie = new CookieContainer();
NameValueCollection col = new NameValueCollection();
col["MAX_FILE_SIZE"] = "3145728";
col["refer"] = "";
col["brand"] = "";
col["optimage"] = "1";
col["rembar"] = "1";
col["submit"] = "host it!";
List<string> l = new List<string>();
switch (fileName.Substring(fileName.Length - 3, 3))
{
case "jpg":
contentType = "image/jpeg";
break;
case "peg":
contentType = "image/jpeg";
break;
case "gif":
contentType = "image/gif";
break;
case "png":
contentType = "image/png";
break;
case "bmp":
contentType = "image/bmp";
break;
case "tif":
contentType = "image/tiff";
break;
case "iff":
contentType = "image/tiff";
break;
default:
contentType = "image/unknown";
break;
}
string resp;
col["optsize"] = "resample";
resp = UploadFileEx(fileName,
"http://www.imageshack.us/index.php",
"fileupload",
contentType,
col,
cookie);
return resp;
}
catch (Exception ex)
{
return "";
}
}
public static string UploadFileEx(string uploadfile, string url,
string fileFormName, string contenttype, System.Collections.Specialized.NameValueCollection querystring,
CookieContainer cookies)
{
if ((fileFormName == null) ||
(fileFormName.Length == 0))
{
fileFormName = "file";
}
if ((contenttype == null) ||
(contenttype.Length == 0))
{
contenttype = "application/octet-stream";
}
string postdata;
postdata = "?";
if (querystring != null)
{
foreach (string key in querystring.Keys)
{
postdata += key + "=" + querystring.Get(key) + "&";
}
}
Uri uri = new Uri(url + postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("\r\n");
sb.Append("\r\n");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
FileStream fileStream = new FileStream(uploadfile,
FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length +
boundaryBytes.Length;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096,
(int)fileStream.Length))];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
}
There is example code on CodeProject that reimplements WebClient.UploadFile "with more" using just HttpwebRequest and friends, which at first glance looks like it uses features that are available in the Compact Framework. You could check the code works with the full framework on a PC and use a tool like Fiddler to check what goes over the wire., before then compiling for the Compact Framework.