Byte[] Array to String - c#

I want to output a Byte[] array to a string so I can send it along a HTTPRequest. Can it be done? And will the server pick up the data and create a file from it? Or does some special encoding need to be done?
The file is an image. At the moment I have:
Byte[] fBuff = File.ReadAllBytes("C:/pic.jpeg");
I need to take what's in fBuff and output it to send along a post request.

Use the Convert.ToBase64String method
Byte[] fBuff = File.ReadAllBytes("C:/pic.jpeg");
String base64 = Convert.ToBase64String(fBuff);
This way the string will as compact as posible and is sort of the "standard" way to writing bytes to string and back to bytes.
To convert back to bytes use Convert.FromBase64String:
String base64 = ""; // get the string
Byte[] fBuff = Convert.FromBase64String(base64);

You could just create a String where each byte is a character of the String. If you do the same opposite procedure at the receiver you will not have any problems (I have done something similar but in Java).

Convert.ToBase64String looks like your best option to store the bytes in a transmittable array, you should look into these functions.

If you are sending just the file, you can use the UploadFile method of the WebClient class:
using (WebClient client = new WebClient) {
client.UploadFile("http://site.com/ThePage.aspx", #"C:\pic.jpeg");
}
This will post the file as a regular file upload, just as from a web page with a file input. On the receiving server the file comes in the Request.Files collection.

Any reason of not using the WebClient upload file?

Related

C# fetch remote text and interpret bytes to put in local byte array

I have a text file on a remote box, that I want to fetch over http, and place into a byte array.
The remote file looks like this:
byte[] buf = new byte[510] { 0xfc,0x48,0x83,0xe4,0xf0,0xe8,0xcc,...};
I can modify it to a format that would be easier to handle.
I have tried
WebClient wc = new WebClient();
buf = wc.DownloadData("http://ip/csharp.txt");
What's the best way of going about this?
Note I'm not looking to convert the text to bytes, I'm looking for c# to interpret the bytes already in the text file, and place them in a byte array.

Get the Image as a byte and send to Facebook Api

I need to send an image as a Byte Array to facebook API. I try to get the file from my Mac and send it but it is breaking in second line when it is reading file.
string fileName = Path.GetFileName(request.PhotoUrl);
byte[] photoContent = File.ReadAllBytes(fileName);
I am using Mac, so my path is looks like:
"photoUrl": "/Users/myname/Documents/test.png"
It is bringing fileName is but braking in second line.
Path.GetFileName() should be returning the filename and its extension. So in your case, fileName will be set to test.png Therefore when you try to read the file your call to File.ReadAllBytes(fileName) will fail unless you are running the program from the same folder as the picture file. Instead of using Path.GetFileName() you could use Path.GetFullPath() or even just pass the PhotoUrl value to the ReadAllBytes function.
Microsoft documentation for
GetFullPath(): https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfullpath?view=netcore-3.1
GetFileName(): https://learn.microsoft.com/en-us/dotnet/api/system.io.path.getfilename?view=netcore-3.1

How to read a binary stream from C# BinaryWriter in PHP?

Is there anything open source available for this?
or
Is there a way to parse a stream of bytes received from a POST request manually and convert the chunks of bytes to the appropriate data types?
I'm not sure if there is anything open source for this, but PHP does support the needed features out of the box.
the contents of a POST request can be retrieved as follows:
$data = file_get_contents("php://input");
// or to handle the data as a stream
$stream = fopen("php://input", "rb");
The above is the preferred method, as $HTTP_RAW_POST_DATA is deprecated.
The data can then be parsed using the PHP unpack() function.

Using FileReader.readAsDataUrl to upload image to Web Api service

I am trying to use the FileReader to obtain the base-64 representation of an image and submit that to a .net WebApi service for image uploading.
My problem is that the contents of fileReader.result are not valid as a base-64 encoded image, at least according to .net.
I am just using a very simple method, and testing with fiddler to post to the service. If I post the complete result string from filereader.result, I get an error "Invalid length for a Base-64 char array or string" when I try and read the string using FromBase64String.
public void Post([FromBody]string imgString)
{
var myString = imgString.Split(new char[]{','});
byte[] bytes = Convert.FromBase64String(myString[1]);
using (MemoryStream ms = new MemoryStream(bytes))
{
Image image = Image.FromStream(ms);
image.Save("myBlargyImage.jpg");
}
}
Is cut+paste into fiddler doing something to the string that I need to account for here, or is there something else I am not doing correctly? This seems like it should be straightforward: Encode the image as a string, send the string, decode the string, save the image.
For example, using filereader to display a preview of the image on the client, I get the following in filereader.result:
src="data:image/jpeg;base64,/9j/4AAQSkZJRgABAgEAyADIAAD/...oBUA00AqYL/AMCg3//Z"
I have tried both sending the entire string ("data...Z"), and just the Base64 string. Currently, I am splitting the string server side to get the Base64 string. Doing this, I always get the invalid length error.
Alternatively, I have tried sending just the base64 string. Not knowing if the leading / was actually part of the string or not, I deleted it in the post body. Doing THIS, I can actually read the value into a byte array, but then I get an error using Image.FromStream that the array is not a valid image.
So, either I get an error that the entire string as provided by filereader is an invalid length, or, I hack it up and get an error that even if it is a valid length, it is not a valid image (when reading the bytearray). That is what makes me wonder if there is some issue of translation or formatting between the filereader.read, dev tools in chrome, then cutting and pasting into fiddler.
UPDATE:
I tried a more realistic implementation by just taking the filereader.result and putting it in a $.post() call, and it works as expected.
It appears I was right, that I, or notepad++, or fiddler, are doing something to the data when I touch it to cut and paste filereader.result into a service call.
If someone knows exactly what that might be, or how one can verify they are sending a valid base-64 encoding of an image to a service, it might help others who are attempting the same thing in the future.
Again, if in the browser filereader.result yielded 'data:image/jpeg;base64,somestring', I was simply copying that string from the developer tools panel, creating a fiddler call and in the request body including the copied string: "=data:image/jpeg;base64,somestring". Somehow, the base-64 'somestring' was getting munched in the cut+paste.
function readURL(input) {
if (input.files && input.files[0]) {
reader = new FileReader();
reader.onload = function (e) {
$('#imgPreview').attr('src', e.target.result);
$.post('/api/testy/t/4',
{'':e.target.result}
);
};
reader.readAsDataURL(input.files[0]);
reader.onloadend = function (e) {
console.log(e.target.result);
};
}
}
$("#imgUpload").change(function () {
readURL(this);
});
Don't forget to remove the 'noise' from a dataUrl,
For example in
data:image/png;base64,B64_DATA_HERE
you have to remove the data:image/png;base64, part before, so you process only the base 64 portion.
With js, it would be
var b64 = dataUrl.split("base64,")[1];
Hope this helps. Cheers
A data uri is not a base64 encode string, it may contain a base64 encoded string at the end of it. In this case it does, so you need to only send the base64 encoded string part.
var imagestr = datauri.split(',')[1];
sendToWebService(imagestr);
Make sure fiddler is not truncating the Base 64 String

HttpPostedFileBase to byte[] how to keep the encoding?

So, the scenario is this:
A user uploads a file, my code turns this file into an array of bytes, and than the array is passed to an external API. And this works fine.
The problem is that this file contains special characters like æ,ø,å, and when the byte[] is converted into characters again, these characters are replaced by "?".
public void UploadFile(HttpPostedFileBase file){
var binary = new byte[file.ContentLength];
file.InputStream.Read(binary, 0, file.ContentLength;
var result = API.UploadDocument(binary); //Passes the file to the external API
}
Can I add some encoding-info to the byte-array or the InputStream, or is it the API's responsibillity to make sure that the text is properly encoded when converting the byte[] back to characters?
It is API's responsibility to properly convert byte array to chars. If you have access to API code than you should add encoding parameters to UploadDocument method

Categories

Resources