how to utf-8 encode the file name with uploading the file content in multi part post - file-upload

Having uploading file working fine except when the file name is double byte.
The code snippet below shows a possible place to do the file name encoding, but not sure if it is right, or where is the right place to apply "charset=utf-8". Any help is appreciated.
HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String urlString = WebApiConstants.getInstance().getBaseURL();
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "--BoundaryStringUsingCurrentTime”+currentTimeMillis();
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
try {
URL url = new URL(urlString);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
List<BasicNameValuePair> headers = getHeaderNameValuePairs();
for (BasicNameValuePair hdr : headers) {
connection.setRequestProperty(hdr.getName(), hdr.getValue());
}
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
outputStream = new DataOutputStream(connection.getOutputStream());
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"requests\"" + lineEnd);
outputStream.writeBytes("Content-Type: application/json" + lineEnd + lineEnd);
outputStream.writeBytes(getJsonDataString(attachment.getMessageId()));
outputStream.writeBytes(lineEnd + twoHyphens + boundary + lineEnd);
/* ???
// could encode the fail name and put in, not sure if it is right?
String fileNameUtf8 = URLEncoder.encode(fileName, "UTF-8");
outputStream.writeBytes("Content-Disposition: form-data; name=\"file0\";filename=\""
+ fileNameUtf8 + "\"" + lineEnd);
*/
outputStream.writeBytes("Content-Disposition: form-data; name=\"file0\";filename=\""
+ fileName + "\"" + lineEnd);
outputStream.writeBytes("Content-Type: " + mimeType + lineEnd + lineEnd);
FileInputStream fileInputStream = new FileInputStream(new File(pathToFile));
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
buffer = new byte[bufferSize];
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
while (bytesRead > 0) {
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, MAX_BUFFER_SIZE);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
… … …
… … …

You can encode the filename like this:
final private static String hexStr = "0123456789ABCDEF";
private static String MimeEncodeQP(String s)
{
byte[] bytes = s.getBytes("UTF-8");
StringBuilder output = new StringBuilder(12 + (bytes.length * 3));
output.append("=?UTF-8?Q?");
for ( final byte b : bytes )
{
if( b == 32 )
{
output.append('_');
}
else if( ((b >= 33) && (b <= 60)) ||
((b >= 62) && (b <= 126)) )
{
output.append((char) b);
}
else
{
output.append('=')
.append(hexStr.charAt((b & 0xF0) >> 4)
.append(hexStr.charAt(b & 0x0F));
}
}
output.append("?=");
return output.toString();
}
outputStream.writeBytes("Content-Disposition: form-data; name=\"file0\";filename=\"" + MimeEncodeQP(fileName) + "\"" + lineEnd);
Read the following specs for more details:
RFC 2045 "Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies", Section 67 "Quoted-Printable Content-Transfer-Encoding"
RFC 2047 "MIME (Multipurpose Internet Mail Extensions) Part Three: Message Header Extensions for Non-ASCII Text"
RFC 7578 "Returning Values from Forms: multipart/form-data", Section 5.1 "Non-ASCII Field Names and Values".
HTML4, Section 17.13.4.2 "multipart/form-data"
HTML5, Section 4.10.22.7 "Multipart form data"

Related

Sending Files in REST API via Apex

I am integrating with one of the provider who accepts a file to upload in their system. While doing so they require the file to be sent as multipart/form-data in the following format !!
I tried configuring it as MultiPart form data using Base64 String still it is not working !!
-H "accept: application/json"
-H "x-api-key: API_KEY"
-H "x-api-token: API_TOKEN"
-H "Content-Type: multipart/form-data"
-F "file=#b4b35527-522d-4228-a266-bdaa80e28a8b.jpg;type=image/jpeg"
what you are looking for is not supported by the salesforce apex callout.
it's still in the salesforce Idea Exchange here is the link for the same.
https://trailblazer.salesforce.com/ideaView?id=08730000000Kr80AAC
You can vote for it but currently, multipart/form-data header is not supported.
please let me know if you have any questions.
Salesforce does support multipart/form-data but what it doesn't support is sending a Image as Blob.
For my requirement I needed to send the image / PDF / attachment as a form data. I used a slightly modified version of http://www.fishofprey.com/2017/04/steps-required-to-support-posting.html
I got another blob method to include the Images & Attachments as blob. Currently i have not added the codec for videos & other documents, but soon i will be adding those as the API does support that one.
Find here with teh modified version of HttpFormBuilder to include Images & Other Attachments as blob. We just need to add appropriate Codec.
public class HttpFormBuilder_Custom {
private final static string Boundary = '1ff13444ed8140c7a32fc4e6451aa76d';
public static string GetContentType() {
return 'multipart/form-data; charset="UTF-8"; boundary="' + Boundary + '"';
}
private static string SafelyPad(
string value,
string valueCrLf64,
string lineBreaks) {
string valueCrLf = '';
blob valueCrLfBlob = null;
while (valueCrLf64.endsWith('=')) {
value += ' ';
valueCrLf = value + lineBreaks;
valueCrLfBlob = blob.valueOf(valueCrLf);
valueCrLf64 = EncodingUtil.base64Encode(valueCrLfBlob);
}
return valueCrLf64;
}
public static string WriteBoundary() {
string value = '--' + Boundary + '\r\n';
blob valueBlob = blob.valueOf(value);
return EncodingUtil.base64Encode(valueBlob);
}
public static string WriteBoundary(
EndingType ending) {
string value = '';
if (ending == EndingType.Cr) {
value += '\n';
} else if (ending == EndingType.None) {
value += '\r\n';
}
value += '--' + Boundary + '--';
blob valueBlob = blob.valueOf(value);
return EncodingUtil.base64Encode(valueBlob);
}
/**
* Write a key-value pair to the form's body.
*/
public static string WriteBodyParameter(string key, string value) {
string contentDisposition = 'Content-Disposition: form-data; name="' + key + '"';
string contentDispositionCrLf = contentDisposition + '\r\n\r\n';
blob contentDispositionCrLfBlob = blob.valueOf(contentDispositionCrLf);
string contentDispositionCrLf64 = EncodingUtil.base64Encode(contentDispositionCrLfBlob);
string content = SafelyPad(contentDisposition, contentDispositionCrLf64, '\r\n\r\n');
string valueCrLf = value + '\r\n';
blob valueCrLfBlob = blob.valueOf(valueCrLf);
string valueCrLf64 = EncodingUtil.base64Encode(valueCrLfBlob);
content += SafelyPad(value, valueCrLf64, '\r\n');
return content;
}
/**
* Helper enum indicating how a file's base64 padding was replaced.
*/
public enum EndingType {
Cr,
CrLf,
None
}
public static string WriteBlobBodyParameter(string key, string file64, string fileName) {
String mimeType = resolveMimeType(fileName);
string contentDisposition = 'Content-Disposition: form-data; name="' + key + '"; filename="'+fileName+'"';
string contentDispositionCrLf = contentDisposition + '\r\n';
blob contentDispositionCrLfBlob = blob.valueOf(contentDispositionCrLf);
string contentDispositionCrLf64 = EncodingUtil.base64Encode(contentDispositionCrLfBlob);
string content = SafelyPad(contentDisposition, contentDispositionCrLf64, '\r\n');
string contentTypeHeader = 'Content-Type: ' + mimeType;
string contentTypeCrLf = contentTypeHeader + '\r\n\r\n';
blob contentTypeCrLfBlob = blob.valueOf(contentTypeCrLf);
string contentTypeCrLf64 = EncodingUtil.base64Encode(contentTypeCrLfBlob);
content += SafelyPad(contentTypeHeader, contentTypeCrLf64, '\r\n\r\n');
integer file64Length = file64.length();
String last4Bytes = file64.substring(file64.length()-4,file64.length());
// Avoid padding the file data with spaces, which SafelyPad does
// http://salesforce.stackexchange.com/a/33326/102
EndingType ending = EndingType.None;
if (last4Bytes.endsWith('==')) {
last4Bytes = last4Bytes.substring(0,2) + '0K';
file64 = file64.substring(0,file64.length()-4) + last4Bytes;
ending = EndingType.CrLf;
} else if (last4Bytes.endsWith('=')) {
last4Bytes = last4Bytes.substring(0,3) + 'N';
file64 = file64.substring(0,file64.length()-4) + last4Bytes;
ending = EndingType.Cr;
}
content += file64;
content += WriteBoundary(ending);
return content;
}
private static String resolveMimeType(String fileName) {
String fileType = fileName.substringAfterLast('.');
String mimeType = 'image/png'; // fallback value
if (fileType.equalsIgnoreCase('png')) {
mimeType = 'image/png';
} else if (fileType.equalsIgnoreCase('jpeg') || fileType.equalsIgnoreCase('jpg')) {
mimeType = 'image/jpg';
} else if (fileType.equalsIgnoreCase('pgm')) {
mimeType = 'image/x-portable-graymap';
} else if (fileType.equalsIgnoreCase('ppm')) {
mimeType = 'image/x-portable-pixmap';
}
return mimeType;
}
}

How do I call Pay U Money Server through WCF?

i am creating a wcf service for Pay u Money I wrote same code like asp.net c# for Pay u Money, but using HttpWebRequest I'm facing this error:
SORRY! We were unable to process your payment
Same code I tried in simple asp.net c# and there working fine. Here I don't know what goes wrong, how could I solve this?
enter code here
public PayUMoneyModel PayUMoney(PayUMoneyModel Data)
{
PayUMoneyModel objPayUMoneyModel = new PayUMoneyModel();
action1 = ConfigurationManager.AppSettings["PAYU_BASE_URL"] +
"/_payment";
try
{
string[] hashVarsSeq;
string hash_string = string.Empty;
if (string.IsNullOrEmpty(Data.txnid)) // generating txnid
{
Random rnd = new Random();
string strHash = Generatehash512(rnd.ToString() +
DateTime.Now);
txnid1 = strHash.ToString().Substring(0, 20);
}
else if(Data.txnid!=null)
{
txnid1 = Data.txnid;
}
Data.txnid = txnid1;
Data.key= ConfigurationManager.AppSettings["MERCHANT_KEY"];
string salt= ConfigurationManager.AppSettings["SALT"];
System.Collections.Hashtable data = new System.Collections.Hashtable();
data.Add("key", Data.key);
data.Add("txnid", Data.txnid);
string AmountForm = Convert.ToDecimal(Data.amount).ToString("g29");// eliminating trailing zeros
//amount.Text = AmountForm;
data.Add("amount", 1.00);
data.Add("firstname", Data.firstname);
data.Add("email", Data.email);
data.Add("phone", Data.phone);
data.Add("productinfo", Data.productinfo);
data.Add("surl", Data.surl);
data.Add("furl", Data.furl);
data.Add("lastname", Data.lastname);
data.Add("curl", Data.curl);
data.Add("address1", Data.address1);
data.Add("address2", Data.address2);
data.Add("city", Data.city);
data.Add("state", Data.state);
data.Add("country",Data.country);
data.Add("zipcode", Data.zipcode);
data.Add("udf1", Data.udf1);
data.Add("udf2", Data.udf2);
data.Add("udf3", Data.udf3);
data.Add("udf4", Data.udf4);
data.Add("udf5", Data.udf5);
data.Add("pg", Data.pg);
data.Add("service_provider", "payu_paisa");
hash_string = Data.key + "|" + Data.txnid + "|" + AmountForm + "|" + Data.productinfo+ "|" + Data.firstname + "|" + Data.email + "|||||||||||" + salt;
string hash = Generatehash512(hash_string);
data.Add("hash", hash);
data.Add("abc", hash_string);
string strForm = PreparePOSTForm(action1, data);
if (strForm != "")
{
var httpWebRequest = (HttpWebRequest)WebRequest.Create(action1);
// httpWebRequest.ContentType = "text/html";
httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.ContentLength = strForm.Length;
string Json = "";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
streamWriter.Write(strForm,0,strForm.Length);
streamWriter.Flush();
streamWriter.Close();
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
Json = streamReader.ReadToEnd().Replace(";", "");
}
}
HttpContext.Current.Response.Write(Json);
}
}
catch(Exception ex)
{
throw ex;
}
return objPayUMoneyModel;
}
this is my Post Form Method
private string PreparePOSTForm(string url, System.Collections.Hashtable data) // post form
{
//Set a name for the form
string formID = "PostForm";
//Build the form using the specified data to be posted.
StringBuilder strForm = new StringBuilder();
strForm.Append("<form id=\"" + formID + "\" name=\"" +
formID + "\" action=\"" + url +
"\" method=\"POST\">");
foreach (System.Collections.DictionaryEntry key in data)
{
strForm.Append("<input type=\"hidden\" name=\"" + key.Key +
"\" value=\"" + key.Value + "\">");
}
strForm.Append("</form>");
//Build the JavaScript which will do the Posting operation.
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language='javascript'>");
strScript.Append("var v" + formID + " = document." +
formID + ";");
strScript.Append("v" + formID + ".submit();");
strScript.Append("</script>");
//Return the form and the script concatenated.
//(The order is important, Form then JavaScript)
return strForm.ToString() + strScript.ToString();
}
this is my key and salt provided by Payumoney website:-
Key:-rjQUPktU
Salt:-e5iIg1jwi8

AtTask / Workfront API File Upload

I'm write a generic upload so I can upload items via the API but not having much success. Getting either a 500 unauthorized or 400 bad request. Here's my attempt after a bit of googling. Not sure if this is over complicated. Have also tried a cut down approach. There's a few posts but none that actually work or are confirmed as working. I'll post a simplified version later and I'm aware this will not return a value. Just trying to get passed the exception before I refine.
public JToken DoUpload(string path, string file, params string[] parameters)
{
string result = string.Empty;
if (!path.StartsWith("/"))
{
path = "/" + path;
}
string fullUrl = url + path;// +ToQueryString(parameters);
string contentType = "multipart/form-data";
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
wr.ContentType = "multipart/form-data; boundary=" + boundary;
wr.Method = "POST";
//wr.Headers.Add("sessionID","XXXXXXXXXXXXXX"); NEEDED?
Stream rs = wr.GetRequestStream();
rs.Write(boundarybytes, 0, boundarybytes.Length);
string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string formitem = string.Format(formdataTemplate, "uploadedFile", "temp.jpg", contentType);
byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
rs.Write(formitembytes, 0, formitembytes.Length);
rs.Write(boundarybytes, 0, boundarybytes.Length);
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
string header = string.Format(headerTemplate, "uploadedFile", "temp.jpg", contentType);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
rs.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
rs.Write(buffer, 0, bytesRead);
}
fileStream.Close();
byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
rs.Write(trailer, 0, trailer.Length);
rs.Close();
WebResponse wresp = null;
Stream stream2;
StreamReader reader2;
try
{
wresp = wr.GetResponse();
stream2 = wresp.GetResponseStream();
reader2 = new StreamReader(stream2);
}
catch (Exception ex)
{
if (wresp != null)
{
wresp.Close();
wresp = null;
}
}
finally
{
wr = null;
}
return result;
}
Figured out a simpler solution if helps anyone:
public JToken DoUpload(string path, string file, string sessionID){
if (!path.StartsWith("/")){
path = "/" + path;
}
string fullUrl = url + path;
string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(fullUrl);
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
webrequest.Accept = "application/json;charset=UTF-8";
webrequest.Headers.Add("sessionID", sessionID);
// 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("uploadedFile");
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(file));
sb.Append("\"");
sb.Append("\r\n");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
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(file,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);
using (WebResponse response = webrequest.GetResponse())
{
using (Stream responseStream = response.GetResponseStream())
{
return ReadResponse(responseStream);
}
}
}

using AE.Net.Mail how to send mail with image inline

I using AE.Net.Mail in .net project.
I sent html mail and file attachment by gmail api and it work perfect.
But i dont know way to embed an image in body mail with it?
Somebody help me ?
string To = txtTo.Text;
string Subject = txtEmailSubject.Text;
string Body = hdfEmailContentSend.Value;
string InputAttachmentArr = hdfInputAttachmentArr.Value;
var msg = new AE.Net.Mail.MailMessage();
msg.From = new MailAddress("haunguyen1791990#gmail.com", "=?UTF-8?B?" + EncodeTo64UTF8(User.FullName) + "?=");
msg.ReplyTo.Add(msg.From);
msg.To.Add(new MailAddress(To));
msg.Subject = "=?UTF-8?B?" + EncodeTo64UTF8(Subject) + "?=";
msg.Body = Body;
var result = SendMessage(InputAttachmentArr, msg, "");
private Google.Apis.Gmail.v1.Data.Message SendMessage(string InputAttachmentArr, AE.Net.Mail.MailMessage msg, string ThreadId) {
try {
bool isAttackFile = false;
string boundary = "boundary_" + DateTime.Now.ToString("yyyyMMddHHmmss");
var service = CRMGmailUtils.DefineServiceGet(Server.MapPath(".") + "\\client_secret.json");
//get info file attachment
List<string> lstAttachFile = InputAttachmentArr.Split(',').ToList();
lstAttachFile.RemoveAll(item => item.Length == 0);
foreach (var item in lstAttachFile) {
string filePath = Server.MapPath("~/" + "Upload/gmail/" + item);
var bytes = File.ReadAllBytes(filePath);
AE.Net.Mail.Attachment file = new AE.Net.Mail.Attachment(bytes, GetMimeType(item), item, true);
msg.Attachments.Add(file);
isAttackFile = true;
}
var msgStr = new StringWriter();
//if file attachment not exists, set type mail is html
if (!isAttackFile) {
msg.ContentType = "text/html";
}
msg.Save(msgStr);
string data = msgStr.ToString();
//else i customize body mail with new boundary
if (isAttackFile) {
string beginBody = "Content-Type: multipart/alternative; boundary=" + boundary;
//beginBody += "\n\n--" + boundary;
//beginBody += "\nContent-Type: text/plain; charset=UTF-8";
//beginBody += "\n\n*2*";
beginBody += "\n\n--" + boundary;
beginBody += "\nContent-Type: text/html; charset=UTF-8";
string endBody = "\n\n--" + boundary + "--";
msg.Body += endBody;
string parentBoundary = Regex.Match(data, #"----(.*?)--").Groups[1].Value;
Regex rgx = new Regex("----" + parentBoundary);
data = rgx.Replace(data, "----" + parentBoundary + "\n" + beginBody, 1);
}
string raw = Base64UrlEncode(data.ToString());
var result = new Google.Apis.Gmail.v1.Data.Message();
//case send with reply
if (!string.IsNullOrEmpty(ThreadId)) {
result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = raw, ThreadId = ThreadId }, "me").Execute();
} else {
//case send new mail
result = service.Users.Messages.Send(new Google.Apis.Gmail.v1.Data.Message { Raw = raw }, "me").Execute();
}
DeleteAttackFile(lstAttachFile);
return result;
} catch (Exception objEx) {
throw objEx;
}
}

HttpWebRequest works. WebClient.UploadFile doesn't

I thought I figured out a way to simplify my code by using WebClient.UploadFile instead of HttpWebRequest, but I end up getting a file on the server end that is a few dozen bytes too short and corrupted. Any idea where the bug lies?
Thanks
Using HttpWebRequest (works fine):
HttpWebRequest req = (HttpWebRequest)HttpWebRequest
.Create("http://" +
ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash);
req.Method = "POST";
req.ContentType = "binary/octet-stream";
req.AllowWriteStreamBuffering = false;
req.ContentLength = bytes.Length;
Stream reqStream = req.GetRequestStream();
int offset = 0;
while (offset < ____)
{
reqStream.Write(bytes, offset, _________);
_______
_______
_______
}
reqStream.Close();
try
{
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
}
catch (Exception e)
{
_____________
}
return safehash;
Using WebClient (corrupt file on server end):
var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers.Add(HttpRequestHeader.ContentType, "binary/octet-stream");
client.UploadFile(new Uri("http://" +
ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash), filename);
return safehash;
Server side is a WCF service:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "up/file/{fileName}/{hash}")]
void FileUpload(string fileName, string hash, Stream fileStream);
WebClient.UploadFile sends the data in a multipart/form-data format. What you want to use to have the equivalent to the code using HttpWebRequest is the WebClient.UploadData method:
var client = new WebClient();
client.Encoding = Encoding.UTF8;
client.Headers[HttpRequestHeader.ContentType] = "application/octet-stream";
byte[] fileContents = File.ReadAllBytes(filename);
client.UploadData(new Uri("http://" + ConnectionManager.FileServerAddress + ":" +
ConnectionManager.FileServerPort +
"/binary/up/" + category + "/" +
Path.GetFileName(filename) + "/" + safehash), fileContents);