Here is my webapi code that is correct i check that i post the
image using postman..how to send image to webapi image save is already work .but i need how to post image from xamrine to webapi request.
[HttpPost]
public ActionResult PostData([System.Web.Http.FromBody] string Name,HttpPostedFileBase Picture)
{
ResponseModel response = new ResponseModel();
try
{
//using (AndroidApiPostEntities db = new AndroidApiPostEntities())
//{
Dictionary<dynamic, dynamic> dic = new Dictionary<dynamic, dynamic>();
string img = "";
img = ImageUpload(Picture);
PostPicture p = new PostPicture();
p.Name = Name;
p.Picture = img;
//db.PostPictures.Add(p);
//db.SaveChanges();
response.error = false;
response.message = "data added successfully.";
dic.Add("Id", 0);
dic.Add("Name", p.Name);
dic.Add("Picture", p.Picture);
response.data = dic;
return Json(response, JsonRequestBehavior.AllowGet);
//}
}
catch (Exception ex)
{
response.error = true;
response.message = "inner exp: " + ex.InnerException.Message + " /second/: " + Convert.ToString(ex.InnerException);
return Json(response, JsonRequestBehavior.AllowGet);
}
}
private string ImageUpload(HttpPostedFileBase img)
{
string fileName;
string extension = System.IO.Path.GetExtension(img.FileName);
Random rnd = new Random();
fileName = "b" + rnd.Next(1000).ToString("000") + extension; //Create a new Name for the file due to security reasons.
// string fileName = Guid.NewGuid().ToString() + ImageName;
//var path = Path.Combine(Directory.GetCurrentDirectory(), "images", fileName);
//string fileName = Guid.NewGuid().ToString() + ImageName;
string physicalPath = Server.MapPath("/images/" + fileName);
//string physicalPath = "~/images/" + fileName;
// save image in folder
img.SaveAs(physicalPath);
return fileName;
}
Now here is my xamrine button click code how to post image or how to convert image to post it also hit the api here is code but i face image error i face null picture on webapi
private async void btnsubmit_Clicked(object sender, EventArgs e)
{
try
{
string picc = MyImage.Source.ToString();
PostUserAsync(txtName.Text, "");
}
catch (Exception ex)
{
await DisplayAlert("Error", ex.InnerException.ToString(), "OK");
}
}
static MediaFile files;
public async void PostUserAsync(string name, string pic)
{
string Host = "http://dxxx5.expxxxxxxxion.com/Home/PostData";
var client = new HttpClient();
var ss=MyImage.Source = ImageSource.FromStream(() =>
{
var stream = files.GetStream();
return stream;
});
byte[] file = File.ReadAllBytes(files.Path);
WebClient webClient = new WebClient();
var fileData = webClient.Encoding.GetString(file);
var fileName = System.IO.Path.GetFileNameWithoutExtension(files.Path);
var model = new PostPicture
{
Name = name,
Picture = file
};
var json = JsonConvert.SerializeObject(model);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var response = client.PostAsync(Host, httpContent).Result;
string res = "";
using (HttpContent content = response.Content)
{
// ... Read the string.
Task<string> result = content.ReadAsStringAsync();
res = result.Result;
}
var jsoss = JsonConvert.DeserializeObject(res);
//var rootObj = JsonConvert.DeserializeObject<PostPicture>(File.ReadAllText(res));
string f = jsoss.ToString();
await DisplayAlert("Successfull", f, "OK");
}
Related
I want to translate single document from one language to another please guide me how to do that i have done translating all the files in azure blob storage but not able to find to translate single file.
please find below code and let me know the changes.
string _FileName = Path.GetFileName(file.FileName);
fileName = _FileName;
string _path = Path.Combine(Server.MapPath("~/UploadedFiles"), _FileName);
file.SaveAs(_path);
string route = "/batches";
string endpoint = "https://translator.cognitiveservices.azure.com/translator/text/batch/v1.0";
string filePath = UploadToAzureStorageAccount.UploadDocument(_path, "uploadeddocs");
string subscriptionKey = "key";
string json = ("" +
"{\"inputs\": " +
"[{\"storageType\": \"File\","+"\"source\": " +
"{\"sourceUrl\": \"https://cdposticketsstorage.blob.core.windows.net/uploadeddocs/test.docx?sp=r&st=2022-03-08T08:13:18Z&se=2022-03-08T16:13:18Z&spr=https&sv=2020-08-04&sr=b&sig=Pt68ogFCj6WSgEBUWI95YJ4GudOcyhEW1cgVXmFCing%3D\"," +
"\"storageSource\": \"AzureBlob\"" +
"}," +
"\"targets\": " +
"[{\"targetUrl\": \"https://cdposticketsstorage.blob.core.windows.net/translateddocs/translate.docx?sp=rcw&st=2022-03-08T11:15:45Z&se=2022-03-08T19:15:45Z&spr=https&sv=2020-08-04&sr=b&sig=QM2FhLxOIE%2FLjeLLfYyR2PmfkNb3nm70wZdCveSJC0M%3D\"," +
"\"storageSource\": \"AzureBlob\"," +
"\"language\": \"fr\"}]}]}");
using (var client = new HttpClient())
using (var request = new HttpRequestMessage())
{
StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
request.Method = HttpMethod.Post;
request.RequestUri = new Uri(endpoint + route);
request.Headers.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
request.Content = content;
HttpResponseMessage response = await client.SendAsync(request);
string result = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
Console.WriteLine($"Status code: {response.StatusCode}");
Console.WriteLine();
Console.WriteLine($"Response Headers:");
Console.WriteLine(response.Headers);
}
else
Console.Write("Error");
}
// TextTranslatorAPI client = new TextTranslatorAPI();
//string res = await client.DocumentTranslator(fileName);
//return res;
}
ViewBag.Message = "File Uploaded Successfully!!";
}
catch(Exception e)
{
ViewBag.Message = "File upload failed!!";
}
The Json string has this structure:
{"CODIGO_AGENCIA":"HN001001","CODIGO_USUARIO":"some user","CODIGO_CATEGORIA":1}
This is the parameter asked by the WS:
public async Task SubirImagenCategoria(string JsonString, HttpPostedFileBase Archivo)
//This is what I got so far, the web service returns error that the json string is empty, I am completely lost on how to proceed.
public static async Task<CustomJsonResult> SubirImagenCategoría(int CodigoCategoria, HttpPostedFileBase Archivo)
{
usuario = UtilClass.GetUsuarioSesion();
var modelo = new SUBIR_IMAGEN_CAT();
modelo.CODIGO_AGENCIA = usuario.CodigoAgencia;
modelo.CODIGO_USUARIO = usuario.Nombre;
modelo.CODIGO_CATEGORIA = 1;
CustomJsonResult result = new CustomJsonResult();
try
{
var JsonString = JsonConvert.SerializeObject(modelo);
var formContent = new MultipartFormDataContent("form-data");
StringContent jsonPart = new StringContent(JsonString.ToString());
jsonPart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
jsonPart.Headers.ContentType = new MediaTypeHeaderValue("application/json");
formContent.Add(jsonPart);
/* byte[] Bytes = new byte[Archivo.InputStream.Length + 1];
Archivo.InputStream.Read(Bytes, 0, Bytes.Length);
var fileContent = new ByteArrayContent(Bytes);
fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { FileName = Archivo.FileName };
formContent.Add(fileContent);*/
StreamContent filePart = new StreamContent(Archivo.InputStream);
filePart.Headers.ContentType = new MediaTypeHeaderValue("text/plain");
filePart.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
filePart.Headers.ContentDisposition.FileName = Archivo.FileName;
formContent.Add(filePart);
var test = formContent;
/*HttpContent jsonParam = new StringContent(JsonString);
HttpContent fileStream = new StreamContent(Archivo.InputStream);
formData.Add(jsonParam, "JsonString", "JsonString");
formData.Add(fileStream, "Archivo", "Archivo");*/
/*var values = new Dictionary<string, string>
{
{ "JsonString", ("{\"CODIGO_AGENCIA\":"+usuario.CodigoAgencia+",\"CODIGO_USUARIO\":\""+usuario.Nombre+"\" ,\"CODIGO_CATEGORIA\":\""+CodigoCategoria+"\"}") },
};
HttpContent myBody = new FormUrlEncodedContent(values);*/
var formData = new MultipartFormDataContent();
String url = DataEntityLayer.Database.Environment.getFinalUrl(Util.UtilWS.subirImagenesCategorias);
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(url, formContent);
string stringContent = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CustomJsonResult>(stringContent);
}
catch (Exception ex)
{
result.Error = ex.Message;
}
return result;
}
This is how I tested the WS from postman
After many attempts and almost having a mental & emotional breakdown, it finally worked.
Example 3 from this link worked for me.
public static UsuarioSesion usuario = new UsuarioSesion();
public static async Task<CustomJsonResult> SubirImagenCategoría(int CodigoCategoria, HttpPostedFileBase Archivo)
{
usuario = UtilClass.GetUsuarioSesion();
var modelo = new SUBIR_IMAGEN_CAT();
modelo.CODIGO_AGENCIA = usuario.CodigoAgencia;
modelo.CODIGO_USUARIO = usuario.Nombre;
modelo.CODIGO_CATEGORIA = CodigoCategoria;
CustomJsonResult result = new CustomJsonResult();
try
{
var JsonString = JsonConvert.SerializeObject(modelo);
var formContent = new MultipartFormDataContent();
HttpContent JsonParam = new StringContent(JsonString);
formContent.Add(JsonParam, "JsonString");
var fileContent = new StreamContent(Archivo.InputStream);
fileContent.Headers.Add("Content-Type", "application/octet-stream");
fileContent.Headers.Add("Content-Disposition", "form-data; name=\"Archivo\"; filename=\"" + Archivo.FileName.ToString() + "\"");
formContent.Add(fileContent, "file", Archivo.FileName.ToString());
String url = DataEntityLayer.Database.Environment.getFinalUrl(Util.UtilWS.subirImagenesCategorias);
var myHttpClient = new HttpClient();
var response = await myHttpClient.PostAsync(url, formContent);
string stringContent = await response.Content.ReadAsStringAsync();
result = JsonConvert.DeserializeObject<CustomJsonResult>(stringContent);
}
catch (Exception ex)
{
result.Error = ex.Message;
}
return result;
}
I am trying to post one or more files from my local machine to an API with HttpClient, MultipartFormContent and ContentType: "application/octet-stream" but when i do postSync and call an API from a local Winform application, the result of the task (var response = task.Result;) says that it is "Unsopported Type File" StatusCode: 415. I tried with ByteArrayContent but was still unsuccessful.
This is my code:
bool Upload(string url, string path, string localFilename, string fileName, string projectId, string folderId)
{
Boolean isFileUploaded = false;
string xapiKey = "-----";
try
{
HttpClient httpClient = new HttpClient();
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.Add("x-api-key", xapiKey);
var fileInfo = new FileInfo(localFilename);
FileUpload uploadResult = null;
bool _fileUploaded = false;
//Extract content file
FileStream fileStream = File.OpenRead(path);
var streamContent = new StreamContent(fileStream);
streamContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data");
streamContent.Headers.ContentDisposition.FileName = "\"" + Path.GetFileName(path) + "\"";
streamContent.Headers.ContentType = new MediaTypeHeaderValue("application/octetstream");
string boundary = Guid.NewGuid().ToString();
MultipartFormDataContent content = new MultipartFormDataContent(boundary);
content.Headers.Remove("Content-Type");
content.Headers.TryAddWithoutValidation("Content-Type", "mulitpart/form-data; boundary=" + boundary);
content.Add(streamContent);
//content.Add(new StreamContent(fileStream), "\"file\"", string.Format("\"{0}\"", fileName + fileInfo.Extension));
Task taskUpload = httpClient.PostAsync(url, content).ContinueWith(task =>
{
if (task.Status == TaskStatus.RanToCompletion)
{
var response = task.Result;
if (response.IsSuccessStatusCode)
{
uploadResult = response.Content.ReadAsAsync<FileUpload>().Result;
if (uploadResult != null)
_fileUploaded = true;
}
}
fileStream.Dispose();
});
taskUpload.Wait();
if (_fileUploaded)
isFileUploaded = true;
httpClient.Dispose();
}
catch (Exception ex)
{
isFileUploaded = false;
throw new Exception(ex.Message);
}
return isFileUploaded;
}
I'm working on UWP apps, In that i need to upload the image for that i'm calling the web service to post the details. I'm using the below code to serialize the image.
byte[] fileBytes = null;
using (var stream = await file.OpenReadAsync())
{
fileBytes = new byte[stream.Size];
using (var reader = new DataReader(stream))
{
await reader.LoadAsync((uint)stream.Size);
reader.ReadBytes(fileBytes);
}
}
docs.Document = fileBytes;
docs.DocumentName = file.Name;
docs.DocumentTypeOtherDescription = "ProfilePicture";
var docsAsJson = JsonConvert.SerializeObject(docs);
StringContent stringContent = new StringContent(docsAsJson, System.Text.Encoding.UTF8);
ByteArrayContent byteContent = new ByteArrayContent(fileBytes);
MultipartFormDataContent httpContent = new MultipartFormDataContent();
httpContent.Add(byteContent, file.Name);
httpContent.Add(stringContent);
using (var httpClient = new HttpClient())
{
var request = new HttpRequestMessage {Method = HttpMethod.Post};
request.Headers.Add("authorization", App.TokenType + " " + App.AccessToken);
request.RequestUri = new Uri(App.BaseUrl + "api/User/UploadUserDocument");
request.Content = httpContent;
request.Content.Headers.Add(#"Content-Length", fileBytes.Length.ToString());
var response = httpClient.SendAsync(request).Result;
var data = response.Content.ReadAsStringAsync();
if (response.IsSuccessStatusCode)
{
}
}
This is my side to serialize the image and in service side they deserialize the image and saved in database. But i'm getting StatusCode: 500, ReasonPhrase: 'Internal Server Error' this error, Any one please help me to solve this issue.
Here is my Service Code:
public IHttpActionResult UpdateUserWithProfilePic(FormData userviewmodel)
{
var error = string.Empty;
var userJson = new StringBuilder();
foreach (var items in userviewmodel.Fields)
{
if (items.Name == "}")
{
if (!userJson.ToString().EndsWith(",")) continue;
userJson.Remove(userJson.Length - 1, 1);
userJson.Append("}");
}
else
userJson.Append((items.Name.Replace("%22", "\"")) + ":" + items.Value);
}
var userView = JsonConvert.DeserializeObject<UserViewModel>(userJson.ToString());
var result = UpdateUser(userView, error);
if (result.ResultType != ResultType.Success) return daHttpActionResult(result.Result, result);
if (userviewmodel.Files != null && userviewmodel.Files.Count > 0)
{
userView.ProfileDocument = new UserDocument
{
DocumentName = userviewmodel.Files[0].Name,
Document = userviewmodel.Files[0].Value.Buffer,
UserID = UserId,
DocumentType = DocumentTypeEnum.ProfilePicture,
DocumentTypeOtherDescription = userviewmodel.Files[0].Value.MediaType,
};
}
return AdHttpActionResult(result.Result, result);
}
Thanks & Regards,
Cristina
Im trying out the Convertapi in a Windows store App project, and i want to send a .docx file and get a pdf file in return, im trying to do a post but im not sure how its done, this is what i have so far, but its not working.
private async Task GeneratePdfContract(string path) {
try {
var data = new List < KeyValuePair < string, string >> {
new KeyValuePair < string, string > ("Api", "5"),
new KeyValuePair < string, string > ("ApiKey", "419595049"),
new KeyValuePair < string, string > ("File", "" + stream2),
};
await PostKeyValueData(data);
} catch (Exception e) {
Debug.WriteLine(e.Message);
}
}
private async Task PostKeyValueData(List < KeyValuePair < string, string >> values) {
var httpClient = new HttpClient();
var response = await httpClient.PostAsync("http://do.convertapi.com/Word2Pdf", new FormUrlEncodedContent(values));
var responseString = await response.Content.ReadAsStringAsync();
}
How should i do my post to send a .docx file and get a .pdf file in return?
Edit:
private async Task GeneratePdfContract(string path)
{
try
{
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "413595149")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
StorageFolder currentFolder = await ApplicationData.Current.LocalFolder.GetFolderAsync(Constants.DataDirectory);
StorageFile outputFile = await currentFolder.GetFileAsync("file.docx");
byte[] fileBytes = await outputFile.ToBytes();
//multipartFormDataContent.Add(new ByteArrayContent(FileIO.ReadBufferAsync(#"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
multipartFormDataContent.Add(new ByteArrayContent(fileBytes));
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path2 = Path.Combine(#"C:\", paths);
StorageFile sampleFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(#"C:\Users\Thought\AppData\Local\Packages\xxxxx_apk0zz032bzya\LocalState\Data\");
await FileIO.WriteBytesAsync(sampleFile, await response.Content.ReadAsByteArrayAsync());
}
else
{
Debug.WriteLine("Status Code : {0}", response.StatusCode);
Debug.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}
}
catch (Exception e)
{
Debug.WriteLine(e.Message);
}
}
#Tomas tried to adapt your answer a bit since there doesn't seem to be a "File.ReadAllBytes" on windows store apps, im getting this response tho :\
You can't pass file stream as string to HttpClient. Just use WebClient.UploadFile method which also support asynchronous uploads.
using (var client = new WebClient())
{
var fileToConvert = "c:\file-to-convert.docx";
var data = new NameValueCollection();
data.Add("ApiKey", "413595149");
try
{
client.QueryString.Add(data);
var response = client.UploadFile("http://do.convertapi.com/word2pdf", fileToConvert);
var responseHeaders = client.ResponseHeaders;
var path = Path.Combine(#"C:\", responseHeaders["OutputFileName"]);
File.WriteAllBytes(path, response);
Console.WriteLine("The conversion was successful! The word file {0} converted to PDF and saved at {1}", fileToConvert, path);
}
catch (WebException e)
{
Console.WriteLine("Exception Message :" + e.Message);
if (e.Status == WebExceptionStatus.ProtocolError)
{
Console.WriteLine("Status Code : {0}", ((HttpWebResponse)e.Response).StatusCode);
Console.WriteLine("Status Description : {0}", ((HttpWebResponse)e.Response).StatusDescription);
}
}
}
The example using HttpClient()
using (var client = new System.Net.Http.HttpClient())
{
using (var multipartFormDataContent = new MultipartFormDataContent())
{
var values = new[]
{
new KeyValuePair<string, string>("ApiKey", "YourApiKey")
};
foreach (var keyValuePair in values)
{
multipartFormDataContent.Add(new StringContent(keyValuePair.Value), String.Format("\"{0}\"", keyValuePair.Key));
}
multipartFormDataContent.Add(new ByteArrayContent(File.ReadAllBytes(#"C:\test.docx")), '"' + "File" + '"', '"' + "test.docx" + '"');
const string requestUri = "http://do.convertapi.com/word2pdf";
var response = await client.PostAsync(requestUri, multipartFormDataContent);
if (response.IsSuccessStatusCode)
{
var responseHeaders = response.Headers;
var paths = responseHeaders.GetValues("OutputFileName").First();
var path = Path.Combine(#"C:\", paths);
File.WriteAllBytes(path, await response.Content.ReadAsByteArrayAsync());
}
else
{
Console.WriteLine("Status Code : {0}", response.StatusCode);
Console.WriteLine("Status Description : {0}", response.ReasonPhrase);
}
}
}