i m developing a C# Window Application which uses web service as it's back end,
how to get image from specified URL:
the image on server is in JPEG Format
var client = new RestClient();
client.BaseUrl = "http://www.*****.com/images/12345.jpg";
var request = new RestRequest();
IRestResponse response = client.Execute(request);
Using RestSharp I did it this Way
var client = new RestClient();
client.BaseUrl = "http://www.abcd.com/image1.jpg";
var request = new RestRequest();
picturebox1.Image = new Bitmap(new MemoryStream(client.DownloadData(request)));
Showing Image at Picture Box
If the client has the image URL, why not just use HTTP to download it? Or are you saying that the images will always reside on the same server that the WebService is running on, and that the WebService method should accept a URL, translate it to a local path, and return the image as a byte array?
We have a method of our WSDL WebService that does about the same thing, we don't include the protocol and host portions of the URL (they'd be redundant.)
[WebMethod]
public byte[] GetPicture(string ImageURL)
{
if (ImageURL.StartsWith("http"))
return new byte[0];
string tmp = System.Web.Hosting.HostingEnvironment.MapPath("/" + ImageURL);
string FileName = Microsoft.JScript.GlobalObject.unescape(tmp);
if (System.IO.File.Exists(FileName))
{
FileStream fs = System.IO.File.OpenRead(FileName);
byte[] buf = new byte[fs.Length];
fs.Read(buf, 0, (int)fs.Length);
fs.Close();
return buf;
}
else
return new byte[0];
}
Does that answer your question?
Related
I am using RestSharp to call .NET Web API.
I am sending the uploaded excel file to web api. Below code works perfectly fine on local machine.
But on the server, we don't have permission to save the uploaded file.
I am looking for alternate method for restRequest.AddFile("content", location) that accept HttpPostedFileBase postedFile = httpContext.Request.Files[0].
RestClient restClient = new RestClient("http://localhost:56360");
RestRequest restRequest = new RestRequest("api/excelupload/Upload");
int readWriteTimeout = restRequest.ReadWriteTimeout > 0
? restRequest.ReadWriteTimeout
: ReadWriteTimeout;
restRequest.ReadWriteTimeout = readWriteTimeout;
restRequest.Method = Method.POST;
restRequest.AddHeader("Content-Type", "multipart/form-data");
restRequest.AddFile("content", location);
restRequest.AddParameter("DetailLineNumber", "4");
var response = restClient.Execute(restRequest);
File reading on API.
foreach (var content in provider.Contents)
{
if (!string.IsNullOrWhiteSpace(content.Headers.ContentDisposition.FileName))
{
postedData.File = await content.ReadAsByteArrayAsync();
}
}
I have not used RestSharp for a while. Could you use a Stream? Something like this:
public RestRequest CreateUploadFileRequest(string path, string filename, Stream fileStream)
{
var request = new RestRequest (Method.POST);
request.Timeout = int.MaxValue; //test
request.Resource = "/files/{path}";
request.AddParameter ("path", path, ParameterType.UrlSegment);
//Need to add the "file" parameter with the file name
request.AddParameter ("file", filename);
request.AddFile ("file", s => StreamUtils.CopyStream (fileStream, s), filename);
return request;
}
I wanted to make an api call equivalent to the given image (api call made from postman) using WebClient or HttpClient. I want to send a file and a text together in one single api call.
You can save image via api call by HttpClient . here is the code:
Send file to the API
var content = new ByteArrayContent(filedata);
content.Headers.ContentType = new MediaTypeHeaderValue(BE.Common.ContentType.appjson);
using (var client = new HttpClient())
{
aPIRequestfile.FileName = filename;
aPIRequestfile.UserId = CurrentSession.Instance.VerifiedUser.UserDetailId;
aPIRequestfile.ContentType = contentType;
aPIRequestfile.IsProfile = isProfile;
client.DefaultRequestHeaders.Add("FileDetails", JsonConvert.SerializeObject(aPIRequestfile));
var ApiRequest = client.PostAsync(apiUrl, content);
if (ApiRequest != null)
{
if (ApiRequest.Result.StatusCode == HttpStatusCode.OK)
{
RepsonseMsg = ApiRequest.Result.Content.ReadAsStringAsync().Result;
}
else
RepsonseMsg = BE.ResultStatus.Failed.ToString();
}
}
Receive by API
byte[] filebytes = Request.Content.ReadAsByteArrayAsync().Result;
you will receive byte and then can save it.
I am trying to send image to python code from Xamarin forms (cross platform), I'm using flask-restful (python API) to build web server and call it from the Xamarin app , so first I converted image to base 64:
Image2.Source = ImageSource.FromStream(() => file.GetStream());
var stream = file.GetStream();
var bytes = new byte[stream.Length];
await stream.ReadAsync(bytes, 0, (int)stream.Length);
base64 = System.Convert.ToBase64String(bytes);
and the post code in xamarin:
var imageContent = new MultipartFormDataContent
{
{ new StringContent(base64), "ImageData" }
};
var httpClient = new HttpClient();
var imageResponse = await httpClient.PostAsync("http://localhost:52524/", imageContent);
//
var resultImageContent = imageResponse.Content.ReadAsStringAsync().Result;
if (resultImageContent != null)
{
//some code here
}
now how I can receive the image from the python code.
I have a WCF service running which takes an image file and stores it in the local file system. It is hosted by a console application and runs in the local computer. The code for which is as below.
Iservice.cs
[ServiceContract]
public interface IImageUpload
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "FileUpload/{fileName}")]
void FileUpload(string fileName, Stream fileStream);
}
Service.cs
public class ImageUploadService : IImageUpload
{
public void FileUpload(string fileName, Stream fileStream)
{
FileStream fileToupload = new FileStream("C:\\ImageProcessing\\Images\\Destination\\" + fileName, FileMode.Create);
byte[] bytearray = new byte[5000000];
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = fileStream.Read(bytearray, 0, bytearray.Length);
totalBytesRead += bytesRead;
} while (bytesRead > 0);
fileToupload.Write(bytearray, 0, bytearray.Length);
fileToupload.Close();
fileToupload.Dispose();
}
}
console program.cs to host
static void Main(string[] args)
{
string baseAddress = "http://192.168.1.4:8000/Service";
WebHttpBinding wb = new WebHttpBinding();
wb.MaxBufferSize = 4194304;
wb.MaxReceivedMessageSize = 4194304;
wb.MaxBufferPoolSize = 4194304;
ServiceHost host = new ServiceHost(typeof(ImageUploadService), new Uri(baseAddress));
host.AddServiceEndpoint(typeof(IImageUpload), wb, "").Behaviors.Add(new WebHttpBehavior());
//host.AddServiceEndpoint(typeof(IImageUpload), new WebHttpBinding(), "").Behaviors.Add(new WebHttpBehavior());
host.Open();
Console.WriteLine("Host opened");
Console.ReadKey(true);
}
Now I have a C# client which is just a simple windows form with a button to upload that talks with this service. It takes a file from its local system and sends it to the service. Code is as below.
private void button1_Click(object sender, EventArgs e)
{
byte[] bytearray = null;
string name = "PictureX.jpg";
Image im = Image.FromFile("C:\\ImageProcessing\\Images\\Source\\Picture1.jpg"); // big file
bytearray = imageToByteArray(im);
string baseAddress = "http://192.168.1.4:8000/Service/FileUpload/";
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(baseAddress + name);
request.Method = "POST";
request.ContentType = "text/plain";
request.ContentLength = bytearray.Length;
Stream serverStream = request.GetRequestStream();
serverStream.Write(bytearray, 0, bytearray.Length);
serverStream.Close();
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
int statusCode = (int)response.StatusCode;
StreamReader reader = new StreamReader(response.GetResponseStream());
}
}
public byte[] imageToByteArray(Image imageIn)
{
MemoryStream ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
return ms.ToArray();
}
Both of them are working fine when I am running it on separate visual studio inside the same laptop. I do not have an app.config or web.config in my service. Everything is written in the code.
Entire code can be found in the below link.
https://github.com/logrcubed/ImageprocessingAlgorithm_WCF
Now I hook in a raspberry pi to the same WiFi (read local LAN) and want to write a python script to upload an image from a local folder in Pi to WCF service similar to my C# client. *How to achieve this? What is the python code for getting this done? I am new to python. So any help is appreciated.*
I tried the below approaches as a hit and trial most of which gave 404 errors. I do not understand whether these are right or not. Could anyone help me in converting the webrequest in C# to python?
Poster library
# test_client.py
from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
# Register the streaming http handlers with urllib2
register_openers()
# Start the multipart/form-data encoding of the file "DSC0001.jpg"
# "image1" is the name of the parameter, which is normally set
# via the "name" parameter of the HTML <input> tag.
# headers contains the necessary Content-Type and Content-Length
# datagen is a generator object that yields the encoded parameters
datagen, headers = multipart_encode({"image1": open("/home/pi/test.jpg", "rb")})
# Create the Request object
request = urllib2.Request("http://192.168.1.6:8000/Service/", datagen, headers)
# Actually do the request, and get the response
print urllib2.urlopen(request).read()
urllib2
import urllib2
import MultipartPostHandler
params = {'file':open( "/home/pi/test.jpg" , 'rb')}
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
req = urllib2.Request( "http://192.168.1.6:8000/Service/FileUpload" , params)
text_response = urllib2.urlopen(req).read().strip()
requests
import requests
url = 'http://192.168.1.4:8000/Service'
headers = {'content-type': 'text/plain'}
files = {'file': open('/home/pi/test.jpg', 'rb')}
r = requests.post(url, files=files, headers=headers)
What I’m trying to do is…
Let the user select a PDF file and some other files using a WCF…once they select the file…those files need to be moved from there to a remote server (company hosted). I’m trying to deserialize the data (reading it as bytes) and transferring it over. I created a Form just as a testing purpose and to see how my client is going to work.
When I get the file....I can display the file but I want to get the actual PDF back and I’m not being able to do that. I can open the file in notepad (but its in the byte format) and when I try to open it in PDF it says that the file format is not supported. I’m really confused and don’t know what needs to be done.
Your help will be really appreciated.
Code Snippet:
Client Side:
private void btnUploadFile_Click(object sender, EventArgs e)
{
string pathServer = #"C:\Users\....\Desktop\Test.pdf";
RestClient newClient = new RestClient("http://localhost:...../Service1.svc/DisplayRawData");
var request = new RestRequest(Method.GET);
request.RequestFormat = DataFormat.Json;
request.OnBeforeDeserialization = resp => { resp.ContentType = "application/json"; };
IRestResponse<TempString> newResponse = newClient.Execute<TempString>(request);
//List<TempString> rtrn = (List<TempString>)newResponse.Data;
var responseData = newClient.DownloadData(request);
FileStream fStream = new FileStream(pathServer, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fStream);
bw.Write(responseData);
bw.Close();
foreach (var xbyte in responseData)
{
// fStream.WriteByte(xbyte);
}
//fStream.Flush();
fStream.Close();
Server Side (Service)
public string DisplayRawData()
{
string path = #"C:\basketball.pdf";
byte[] fileToSend = File.ReadAllBytes(path);
string filetoSendB64 = Convert.ToBase64String(fileToSend);
// WebOperationContext.Current.OutgoingResponse.ContentType = "application/pdf";
return filetoSendB64;
}
Interface
//Getting Stream from a File
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "DisplayRawData",
RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
// string DisplayRawData();
string DisplayRawData();
The code is a bit confusing, but I would say it looks like you need to decode the response string from Base64 back to a byte array before writing it to a file.