How to upload image to server using web api? - asp.net-web-api

I am at learning phase of web api and I want to upload image to server using web api in mvc dot net. I have tried much but not getting solution.
In controller I have done this.
string img = username + "_" + labTestId + fb;
var element2 = image;
MemoryStream ms = new MemoryStream(Convert.FromBase64String(element2));
byte[] imagesbytes = ms.ToArray();
string folder_name = "lab-orders";
folder_name = folder_name.ToLower();
string SaveLocation = ServerConfig.BlobPath + folder_name + "/" + fb+imagesbytes;
BlobUploader.UploadTo(folder_name,img, ms);
// var filePath = HttpContext.Current.Server.MapPath("~/Userimage/" + postedFile.FileName + extension);
var filePath = HttpContext.Current.Server.MapPath(SaveLocation + postedFile.FileName + extension);
postedFile.SaveAs(filePath);
How can I upload image to server using web api?

It's not that simple.
In this tutorial You have step by step everything You have to do, to upload image.
In brief:
Create Blob Storage Account, and get access keys.
Save keys in Your web config.
Install WindowsAzureStorage from nuget packege manager
Create blob storage client, get or create blob container
create CloudBlockBlob and upload it.
Edit
Change link to web api tutorial insted of mvc tutorial

Related

Download attachments from Yammer

I am using Web Client to download yammer attachments i tried to use all different URL's available by yammer API / browser :
-download URL
-large preview URL
-right click and copy image URL
file is downloaded with 0 bytes
any suggestion ?
to download Yammer attachments you need both Download URl and Access token as below
string Path = #"C:\SocialMediaDownloads\Yammer\Attachments\"+MessageId;
bool isExists = System.IO.Directory.Exists(Path);
if (!isExists)
System.IO.Directory.CreateDirectory(Path);
WebClient client = new WebClient();
client.BaseAddress = "https://www.yammer.com";
client.Headers["Authorization"] = "Bearer " + accessToken;
client.DownloadFileCompleted += new AsyncCompletedEventHandler(client_DownloadDataCompleted);
client.DownloadFileAsync(new Uri(URL),Path+#"\"+FileName);
return Path;
}

Sending Images to the client from tomcat server

I am building a framework for e-commerce site. I have used jersey to create REST APIs. I need to send images to the clients as per the request.
How can I do so from my application server as Tomcat and jersey as REST API?
Since I am new to this, I have no clue how to send images to an Android client when they are shown as item.
Every resource is identified by the URI, client will ask for a particular image or a bunch of images by quering the URL, So you just need to expose a service, following service is an example to send single image to client.
#GET
#Path("/images/{imageId}")
#Produces("image/png")
public Response downloadImage(#PathParam("imageId") String imageId) {
MultiMediaDB imageDb = new MultiMediaDB();
String filePath = imageDb.getImage(imageId);
File file = new File(filePath);
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename=\"fileName.png\"");
return response.build();
}
MultiMediaDB is my custom class to get the file location from the DB, you can hardcode it as of now for testing purpose like D:\server_image.png.
You need to mention Content-Disposition as an attachment so that file will not be downloaded, instead attached to the form. In android you just need to read inputstream from a HttpURLConnection object and send that to bitmap as shown below
URL url = new URL(BaseUrl + "/images/" + imageId);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
iStream = urlConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(iStream);
The you can set that bitmap to imageview or what ever you have as a container.

How to convert rad controls to images in silverlight

I'm using rad controls(charts and gridview) for developing an application,which i need to export the controls(each) into image.I have tried each control converting them into bytes format and send to webservice and converting them to images but sometime sending the byte data to service throws an error.Is any other way to convert each control into image.I have tried another way like.
Stream fileStream = File.OpenRead(#"\\HARAVEER-PC\TempImages\FlashPivot.png");
//PART 2 - use the stream to write the file output.
productChart.ExportToImage(fileStream, new Telerik.Windows.Media.Imaging.PngBitmapEncoder());
fileStream.Close();
It throwing me an error like cannot access to the folder TempImages.I have given sharing permissions to everyone but it doesn't access the folder.
Any solution is much appreciated.
private BitmapImage CreateChartImages()
{
Guid photoID = System.Guid.NewGuid();
string photolocation = #"D:\Temp\" + photoID.ToString() + ".jpg";
BitmapImage bi = new BitmapImage(new Uri(photolocation, UriKind.Absolute));
using (MemoryStream ms = new MemoryStream())
{
radChart.ExportToImage(ms, new PngBitmapEncoder());
bi.SetSource(ms);
}
return bi;
}

File Download from Azure Blob

Below code is for donwnloading file from azure blob. I have problem with .docx,.xlsx files and that too after deployment only, mean in local machine it is working fine.
The problem is after downloading .xlsx or .docx, when i open that file showing file corrupted popup.
public void DownloadBlob(string blobName)
{
//You have to get values for below items from azure
string accountName = "MyAccName";
string accountPrimaryKey = "MyKey";
string blobContainer = "ContainerName";
CloudStorageAccount account = new CloudStorageAccount(new StorageCredentialsAccountAndKey(accountName, accountPrimaryKey), false);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(blobContainer);
CloudBlob blob = container.GetBlobReference(blobName);
MemoryStream memStream = new MemoryStream();
blob.DownloadToStream(memStream);
Response.ContentType = blob.Properties.ContentType;
Response.AddHeader("Content-Disposition", "Attachment; filename=" + blobName.ToString());
Response.AddHeader("Content-Length", (blob.Properties.Length - 1).ToString());
Response.BinaryWrite(memStream.ToArray());
Response.End();
}
I am sure you have issue with your code as As Steve suggested you are setting length incorrectly.
I worked on similar issue sometime last year and documented the solution in my blog as below:
http://blogs.msdn.com/b/avkashchauhan/archive/2011/04/05/downloading-word-and-excel-files-from-windows-azure-storage-in-a-asp-net-web-role.aspx

Using BackgroundTransferRequest for uploading to Photos to Facebook with Graph API

I am trying to upload photos form Windows phone (mango) to facebook with BackgroundTransferRequest object. This is because I want to upload photos even if the app is not running.
I am using facebook C# SDK to get access token etc and which works great but to upload using this, we need to keep the APP active.
I can use fiddler and create a Post request with access token and upload the image to facebook to a album.
https://graph.facebook.com/178040612256938/Photos/?access_token=AAACEdEose0cBAA4p0Ozqj0H39RP2tGyxdq0LAxoADyBZCPgjgrXMwU93VAOVkulemC3ZC5lVZCTiJ3rYeFXtM67tYNEZBvPQmasbT9AvX
Now, here is my code that I took off of sample here - http://msdn.microsoft.com/en-us/library/hh202959(v=vs.92).aspx
I am not sure how to add headers that fiddler adds OR how to use this for uploading photos to FB. getting 400 as response. Currently the following code can upload photo to my WCF service.
also looked at - BackgroundTransferRequest WP7
IsolatedStorageFileExtensions.SavePicture(Path.Combine(TransfersFiles, picture.FileName), picture.Data);
string fbURL = #"https://graph.facebook.com/106216062727932/Photos/?access_token=AAACEdEose0cBAA4p0Ozqj0H39RP2tGyxdq0LAxoADyBZCPgjgrXMwU93VAOVkulemC3ZC5lVZCTiJ3rYeFXtM67tYNEZBvPQmasbT9AvD";
var transferRequest = new BackgroundTransferRequest(new Uri(fbURL, UriKind.Absolute));
if (!_wifiOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowCellular;
}
if (!_externalPowerOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowBattery;
}
if (!_wifiOnly && !_externalPowerOnly)
{
transferRequest.TransferPreferences = TransferPreferences.AllowCellularAndBattery;
}
//this is the place to upload to Facebook
transferRequest.Method = "POST";
//_OLD transferRequest.UploadLocation = new Uri(TransfersFiles + #"\" + picture.FileName, UriKind.Relative);
transferRequest.UploadLocation = new Uri(TransfersFiles + #"\" + picture.FileName, UriKind.Relative);
string boundary = DateTime.Now.Ticks.ToString("x", CultureInfo.InvariantCulture);
//---
transferRequest.TransferStatusChanged += OnTransferStatusChanged;
transferRequest.TransferProgressChanged += OnTransferProgressChanged;
BackgroundTransferService.Add(transferRequest);

Resources