Send Image to the API using image path that stored in local database - api

I am trying to send image to the API, I have multiple local storage image path which is stored in local
database sqlite and I have to upload these image on one click. in the
local database. replace _mediaFile = await CrossMedia.Current.TakePhotoAsync
with _mediaFile = Image_Path_From_Database
The datatobesync it contain multiple local storage image path from local dat
conn = await DependencyService.Get().GetConnection();
List datatobesync = new List();
datatobesync = (from c in conn.Table<CDCInfo>()
where c.SyncStatus == 0 && c.UserName == Settings.Username
select new CDCInfo
{
PhotoPath = c.PhotoPath,
}
I have a string image path but I am not sure about how
to use this
Using MediaPlugin for opening a gallery or camera. After selecting the
picture I set that picture to _mediafile and added to the content and send it to the API.
Detail Here
these lines of code gets image from the gallery or camra (using MediaPlugin) in a
mediaFile and send it to the API
private MediaFile _mediaFile;
_mediaFile = await CrossMedia.Current.TakePhotoAsync(new Plugin.Media.Abstractions.
StoreCameraMediaOptions
{
Directory = "Sample",
Name = "test.jpg",
AllowCropping = true,
PhotoSize = PhotoSize.Medium
});
var content = new MultipartFormDataContent();
content.Add(new StreamContent(_mediaFile.GetStream()),"\"Files\"", $"\"{_mediaFile.path}\"");
var httpClnt = new HttpClient();
result = await httpClnt.PostAsync(Urle, content);
How can I add image to the content using database path and send it to the API without using MediaPlugin.
I am trying to do something like
foreach (var item in datatobesync)
{
try
{
HttpClient client = new HttpClient();
MultipartFormDataContent content = new
MultipartFormDataContent();
content.Add(new
StreamContent("Here I want to user item.PhotoPath Image path from the database".GetStream()),"\"Files\"",
$"\"{item.PhotoPath}\"");
var httpClnt = new HttpClient();
result = await httpClnt.PostAsync(Urle, content);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
I dont know how to use image path at this line
content.Add(new StreamContent(How_to_User_ImagePath_Her.GetStream()),"\"Files\"",
$"\"{item.PhotoPath}\"");
How to get GetStram() of image path

Related

How to perform POST using .NET Core 6 Minimal API in Azure Blob Storage

I am new to .NET and I have to perform this. Assuming we have the connection string and the Environment variable setup, could someone give me resources or code or guide on how to do it?
I just need to upload a pdf file in Azure Blob Storage using Minimal API
From the Minimal API document, we can see that the Minimal API does not support the binding the IFormFile.
No support for binding from forms. This includes binding IFormFile. We plan to add support for IFormFile in the future.
So, to upload file in the Minimal API, you can get the upload file from the HttpRequest Form. Refer to the following code:
app.MapPost("/upload", (HttpRequest request) =>
{
if (!request.Form.Files.Any())
return Results.BadRequest("At least one fie is need");
//Do something with the file
foreach(var item in request.Form.Files)
{
var file = item;
//insert the file into the Azure storage
}
return Results.Ok();
});
The screenshot as below:
Then, to upload the file to Azure Blob Storage, refer the following tutorial:
Upload images/files to blob azure, via web api ASP.NET framework Web application
Code like this:
CloudStorageAccount storageAccount;
Dictionary<string, object> dict = new Dictionary<string, object>();
string strorageconn = ConfigurationManager.AppSettings.Get("MyBlobStorageConnectionString");
if (CloudStorageAccount.TryParse(strorageconn, out storageAccount))
{
try
{
// Create the CloudBlobClient that represents the
// Blob storage endpoint for the storage account.
CloudBlobClient cloudBlobClient = storageAccount.CreateCloudBlobClient();
// Create a container called 'quickstartblobs' and
// append a GUID value to it to make the name unique.
CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");
await cloudBlobContainer.CreateIfNotExistsAsync();
// Set the permissions so the blobs are public.
BlobContainerPermissions permissions = new BlobContainerPermissions
{
PublicAccess = BlobContainerPublicAccessType.Blob
};
await cloudBlobContainer.SetPermissionsAsync(permissions);
var httpRequest = HttpContext.Current.Request;
foreach (string file in httpRequest.Files)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created);
var postedFile = httpRequest.Files[file];
string imageName = ("images" + serverTime.Year.ToString() + serverTime.Month.ToString() + serverTime.Day.ToString() +
serverTime.Hour.ToString() + serverTime.Minute.ToString() + serverTime.Second.ToString() + serverTime.Millisecond.ToString()
+ postedFile.FileName );
if (postedFile != null && postedFile.ContentLength > 0)
{
int MaxContentLength = 1024 * 1024 * 1; //Size = 1 MB
IList<string> AllowedFileExtensions = new List<string> { ".jpg", ".gif", ".png" };
var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
var extension = ext.ToLower();
if (!AllowedFileExtensions.Contains(extension))
{
var message = string.Format("Please Upload image of type .jpg,.gif,.png.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else if (postedFile.ContentLength > MaxContentLength)
{
var message = string.Format("Please Upload a file upto 1 mb.");
dict.Add("error", message);
return Request.CreateResponse(HttpStatusCode.BadRequest, dict);
}
else
{
CloudBlockBlob cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);
cloudBlockBlob.Properties.ContentType = postedFile.ContentType;
await cloudBlockBlob.UploadFromStreamAsync(postedFile.InputStream);
}
}
var message1 = string.Format("Image Updated Successfully.");
return Request.CreateErrorResponse(HttpStatusCode.Created, message1);
}
var res3 = string.Format("Please Upload a image.");
dict.Add("error", res3);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}
catch (Exception ex)
{
HttpResponseMessage response2 = Request.CreateResponse(HttpStatusCode.BadRequest, ex.InnerException.ToString());
return response2;
}
}
else
{
var res = string.Format("Did not connect successfull.");
dict.Add("error", res);
return Request.CreateResponse(HttpStatusCode.NotFound, dict);
}

ASP.NET Core, Azure storage controller

I have a very newbie question.
I am following this docs "Azure Blob storage client library v12 for .NET" - https://learn.microsoft.com/en-us/azure/storage/blobs/storage-quickstart-blobs-dotnet
When I tested on my console, and my Azure storage, it works.
But I was wondering if I can make a controller out of the suggested 'Main' method?
Because I want these getting and posting to the server actions initiated when the user input changes from the front end side.
This is what the Main method inside of the Program.cs looks like based on the docs
static async Task Main()
{
Console.WriteLine("Azure Blob storage v12 - .NET quickstart sample\n");
string connectionString = Environment.GetEnvironmentVariable("My_CONNECTION_STRING");
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
string containerName = "quickstartblobs" + Guid.NewGuid().ToString();
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
string localPath = "./data/";
string fileName = "quickstart" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
// Write text to the file
await File.WriteAllTextAsync(localFilePath, "Hello, World!");
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
Console.WriteLine("Listing blobs...");
// List all blobs in the container
await foreach (BlobItem blobItem in containerClient.GetBlobsAsync())
{
Console.WriteLine("\t" + blobItem.Name);
}
Console.Write("Press any key to begin clean up");
Console.ReadLine();
string downloadFilePath = localFilePath.Replace(".txt", "DOWNLOAD.txt");
Console.WriteLine("\nDownloading blob to\n\t{0}\n", downloadFilePath);
// Download the blob's contents and save it to a file
BlobDownloadInfo download = await blobClient.DownloadAsync();
using (FileStream downloadFileStream = File.OpenWrite(downloadFilePath))
{
await download.Content.CopyToAsync(downloadFileStream);
downloadFileStream.Close();
}
}
So for example, in my HomeController Can I use post related functions as
[HttpPost]
public void Post([FromBody]string value)
{
//Create a unique name for the container
string containerName = "filedata" + Guid.NewGuid().ToString();
// Create the container and return a container client object
BlobContainerClient containerClient = await blobServiceClient.CreateBlobContainerAsync(containerName);
// Create a local file in the ./data/ directory for uploading and downloading
string localPath = "./data/";
string fileName = "textfile" + Guid.NewGuid().ToString() + ".txt";
string localFilePath = Path.Combine(localPath, fileName);
BlobServiceClient blobServiceClient = new BlobServiceClient(connectionString);
// Get a reference to a blob
BlobClient blobClient = containerClient.GetBlobClient(fileName);
Console.WriteLine("Uploading to Blob storage as blob:\n\t {0}\n", blobClient.Uri);
// Open the file and upload its data
using FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close();
}
Or is this a no-go?
Thanks for helping this super newbie!
So for example, in my HomeController Can I use post related functions Or is this a no-go?
Yes, you can achieve it.
You can use postman to send post request in local to test it. Remember to remove SSL for webserver setting.
Also, change public void Post to public async Task Post and remove using in code:
FileStream uploadFileStream = File.OpenRead(localFilePath);
await blobClient.UploadAsync(uploadFileStream, true);
uploadFileStream.Close()

How download binary files with pentaho?

The Http Client step of pentaho only allows download of text files.
How can I download binary files with Pentaho?
Add a Modified Java Script Value with the following code
var fileURL = "https://hp.imguol.com.br/c/home/b1/2018/05/26/mohamed-salah-chora-apos-se-machucar-em-lance-com-sergio-ramos-1527363329053_300x300.jpg";
var url = java.net.URL(fileURL);
var httpConn = url.openConnection();
// opens input stream from the HTTP connection
var inputStream = httpConn.getInputStream();
var saveFilePath = "d:/myfile10.jpg";
var bis = java.io.BufferedInputStream(inputStream);
var bos = java.io.BufferedOutputStream(java.io.FileOutputStream(java.io.File(saveFilePath)));
var inByte;
while((inByte = bis.read()) != -1) {
bos.write(inByte);
}
bis.close();
bos.close();

download doc file in MVC

I have applicaiton which is the combination of MVC 4 + Web Api + SQL server.
I am trying to download the doc file to MVC but i have tried the below step.
I have Web API where i have written the below code. when i send the rowid it has the value stored in the DB as varbinary. file format can be any thing like .doc,pdf etc ... but however I am looking for the first doc or PDF file format.
When I call the Web api it will create the PDF file and download it , but the file is completely corrupted.
[ResponseType(typeof(MandateExceptionDO))]
[HttpGet]
[Route("api/DealingMandate/GetExceptionDoc/{rowId}")]
public HttpResponseMessage GetExceptionDoc(int rowId)
{
IDealingMandates repository = new DealingMandatesRepository();
List<MandateExceptionDO> mandateexceptiondoc =new List<MandateExceptionDO>();
mandateexceptiondoc = repository.GetExceptionDoc(rowId);
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
//response.Content = new ByteArrayContent(mandateexceptiondoc[0].Content);
//response.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data");
//byte[] fileBytes = System.IO.File.ReadAllBytes(mandateexceptiondoc[0].Content);
response.Content = new ByteArrayContent(mandateexceptiondoc[0].Content);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "testing.pdf";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
//return Ok(mandateexceptiondoc);
return response;
}
I am able to fix this issue on the web api i made the byte as string as show below
String doc = Convert.ToBase64String(customermandate.Content);
and for the MVC side i converted back to byte from the string
var doc = restClient.Execute(request);
var response = doc.Content.Substring(1, doc.Content.Length - 2).Replace(#"\/", "/");
byte[] docBytes = Convert.FromBase64String(response);
if (doc.Content != null && doc.Content.Length > 0 && !string.IsNullOrEmpty(doc.Content))
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename=" + FileName);
Response.BinaryWrite(docBytes);
Response.End();
}

WinRT No mapping for the Unicode character exists in the target multi-byte code page

I am trying to read a file in my Windows 8 Store App. Here is a fragment of code I use to achieve this:
if(file != null)
{
var stream = await file.OpenAsync(FileAccessMode.Read);
var size = stream.Size;
using(var inputStream = stream.GetInputStreamAt(0))
{
DataReader dataReader = new DataReader(inputStream);
uint numbytes = await dataReader.LoadAsync((uint)size);
string text = dataReader.ReadString(numbytes);
}
}
However, an exeption is thrown at line:
string text = dataReader.ReadString(numbytes);
Exeption message:
No mapping for the Unicode character exists in the target multi-byte code page.
How do I get by this?
I managed to read file correctly using similar approach to suggested by duDE:
if(file != null)
{
IBuffer buffer = await FileIO.ReadBufferAsync(file);
DataReader reader = DataReader.FromBuffer(buffer);
byte[] fileContent = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(fileContent);
string text = Encoding.UTF8.GetString(fileContent, 0, fileContent.Length);
}
Can somebody please elaborate, why my initial approach didn't work?
Try this instead of string text = dataReader.ReadString(numbytes):
dataReader.ReadBytes(stream);
string text = Convert.ToBase64String(stream);
If, like me, this was the top result when search for the same error regarding UWP, see the below:
The code I had which was throwing the error (no mapping for the unicode character exists..):
var storageFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);
using (var stream = await storageFile.OpenAsync(FileAccessMode.Read))
{
using (var dataReader = new DataReader(stream))
{
await dataReader.LoadAsync((uint)stream.Size);
var json = dataReader.ReadString((uint)stream.Size);
return JsonConvert.DeserializeObject<T>(json);
}
}
What I changed it to so that it works correctly
var storageFile = await Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.GetFileAsync(fileToken);
using (var stream = await storageFile.OpenAsync(FileAccessMode.Read))
{
T data = default(T);
using (StreamReader astream = new StreamReader(stream.AsStreamForRead()))
using (JsonTextReader reader = new JsonTextReader(astream))
{
JsonSerializer serializer = new JsonSerializer();
data = (T)serializer.Deserialize(reader, typeof(T));
}
return data;
}