Android to WCF: Streaming multi part image and Json string - android

Android to WCF: Streaming multi part image and Json string
I want to create a WCF-RESTful web service method,in which i need to upload an image(multipart-form data) along with some other information (in JSON format). This web service will be accessed by android and iPhone application to send Image and json information as
I want WCF Server Side and Android Code, Help me
I'm trying to upload an image and a text to a wcf service. I create a service to save upload images:
Rest Client Code
protected void Button2_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
MemoryStream mStream = new MemoryStream();
Bitmap bmpPostedImage = new Bitmap(FileUpload1.PostedFile.InputStream);
bmpPostedImage.Save(mStream, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] imageArray = mStream.ToArray();
mStream.Close();
VehicleCheckListTransaction objAttachmentRequestDto = new VehicleCheckListTransaction();
objAttachmentRequestDto.VehicleCheckListTransactionID = 0;
objAttachmentRequestDto.VehicleCheckListID = 2;
objAttachmentRequestDto.TTID = 10;
objAttachmentRequestDto.UserID = 226;
objAttachmentRequestDto.UserTypeID = 4;
objAttachmentRequestDto.ValidTill = "215-05-10";
objAttachmentRequestDto.CurrentDate = "215-07-22";
objAttachmentRequestDto.CurrentStatus = "Yes";
objAttachmentRequestDto.CreatedBy= 226;
objAttachmentRequestDto.ModifiedBy = 226;
objAttachmentRequestDto.CreatedDate = string.Empty;
objAttachmentRequestDto.ModifiedDate = string.Empty;
objAttachmentRequestDto.Notes = "Some Text";
objAttachmentRequestDto.IsActive = true;
objAttachmentRequestDto.FileName = "";
objAttachmentRequestDto.FilePath = "";
objAttachmentRequestDto.VerifiedBy = 226;
var serializer = new DataContractJsonSerializer(typeof(VehicleCheckListTransaction));
var ms = new MemoryStream();
serializer.WriteObject(ms, objAttachmentRequestDto);
ms.Position = 0;
var reader = new StreamReader(ms);
string requestBody = reader.ReadToEnd();
var client = new RestClient();
client.BaseUrl = new Uri("http://localhost:49188/WDS_SERVICE.svc/");
var request = new RestRequest(Method.POST) { DateFormat = DataFormat.Json.ToString(), Resource = "vehiclechecklisttransaction/Add" };
if (requestBody != null)
request.AddParameter("VehicleCheckListTransaction", requestBody);
request.AddFile("file1", imageArray, "NEVER.jpg");
var response = client.Execute(request);
}
}
WCF Service Code
public string UploadPhoto(Stream request)
{
//Read in our Stream into a string...
StreamReader reader = new StreamReader(request);
string JSONdata = reader.ReadToEnd();
// ..then convert the string into a single "wsCustomer" record.
JavaScriptSerializer jss = new JavaScriptSerializer();
Checklist Checklist = jss.Deserialize<Checklist>(JSONdata);
try
{
FileStream targetStream = null;
Stream sourceStream = Checklist.fileContents;
String guid = Guid.NewGuid().ToString();
//get photofolder path
string photofolderName = "Trip\\Android";
string filename = guid + ".JPEG";
string uriPath = "file:\\C:\\inetpub\\wwwroot\\WDS\\Media\\" + photofolderName + "\\" + filename;
string photopath = new Uri(uriPath).LocalPath;
using (targetStream = new FileStream(photopath, FileMode.Create, FileAccess.Write, FileShare.None))
{
//read from the input stream in 6K chunks
//and save to output stream
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
db.Checklists.Add(Checklist);
db.SaveChanges();
return filename + "_" + Checklist.ChecklistID;
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}

Related

Azure http-put UnityWebRequest on android

I'm trying to upload a video to a private Azure blob. The UnityWebRequest works perfectly on PC, but once it's built on an Android device it keeps returning a 403 error.
For debugging I tried to use the normal HttpWebRequest on the android device, with the same settings, which works fine. It's not an option to switch over to HttpWebRequest.
I'm wondering whether the HttpWebRequest has some default options that the UnityWebRequest doesn't, or if perhaps anyone knows of other issues?
HttpWebRequest: Works on both devices
I can provide code if necessary.
[Update]
public IEnumerator PutBlob(string filePath, string blockBlobReference)
{
String httpMethod = "PUT";
Byte[] blobContent = File.ReadAllBytes(filePath);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
String urlPath = String.Format("{0}/{1}", AzureStorageConstants.container, blockBlobReference);
String msVersion = "2009-09-19";
//String msVersion = "2015-02-21";
String dateInRfc1123Format = DateTime.UtcNow.AddHours(1).ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", httpMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri(AzureStorageConstants.BlobEndPoint + urlPath);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = httpMethod;
request.Headers.Add("x-ms-blob-type", blobType);
request.Headers.Add("x-ms-date", dateInRfc1123Format);
request.Headers.Add("x-ms-version", msVersion);
request.Headers.Add("Authorization", authorizationHeader);
request.ContentLength = blobLength;
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(blobContent, 0, blobLength);
yield return requestStream;
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
String ETag = response.Headers["ETag"];
}
}
UnityWebRequest: Works on computer, but not on android
public IEnumerator PutBlob(string filePath, string blockBlobReference)
{
String httpMethod = "PUT";
Byte[] blobContent = File.ReadAllBytes(filePath);
Int32 blobLength = blobContent.Length;
const String blobType = "BlockBlob";
String urlPath = String.Format("{0}/{1}", AzureStorageConstants.container, blockBlobReference);
String msVersion = "2009-09-19";
//String msVersion = "2015-02-21";
String dateInRfc1123Format = DateTime.UtcNow.AddHours(1).ToString("R", CultureInfo.InvariantCulture);
String canonicalizedHeaders = String.Format("x-ms-blob-type:{0}\nx-ms-date:{1}\nx-ms-version:{2}", blobType, dateInRfc1123Format, msVersion);
String canonicalizedResource = String.Format("/{0}/{1}", AzureStorageConstants.Account, urlPath);
String stringToSign = String.Format("{0}\n\n\n{1}\n\n\n\n\n\n\n\n\n{2}\n{3}", httpMethod, blobLength, canonicalizedHeaders, canonicalizedResource);
String authorizationHeader = CreateAuthorizationHeader(stringToSign);
Uri uri = new Uri(AzureStorageConstants.BlobEndPoint + urlPath);
ServicePointManager.ServerCertificateValidationCallback = MyRemoteCertificateValidationCallback;
using (UnityWebRequest webRequest = new UnityWebRequest())
{
webRequest.SetRequestHeader("x-ms-blob-type", blobType);
webRequest.SetRequestHeader("x-ms-date", dateInRfc1123Format);
webRequest.SetRequestHeader("x-ms-version", msVersion);
webRequest.SetRequestHeader("Authorization", authorizationHeader);
UploadHandler uploadHandler = new UploadHandlerRaw(blobContent);
webRequest.uploadHandler = uploadHandler;
uploadHandler.contentType =
webRequest.url = uri.ToString();
webRequest.method = httpMethod;
webRequest.Send();
while (!webRequest.isDone)
{
ProgressBar = webRequest.uploadProgress;
yield return null;
}
}
}

How to upload cordova filetransfer using server asp.net

i am creating an api that will recieve file from cordova file tranfer plugin.But while uploading , we are getting error "[10/19/2016 5:03:33 PM] azad singh: E/FileTransfer: {"target":"http://54.252.109.57:1031/api/Client/SaveDocument","http_status":500,"body":"\"Object reference not set to an instance of an object.\"","code":1,
[10/19/2016 5:03:45 PM] azad singh: Cordova - Camera"
[HttpPost]
[Route("Uploadfile")]
public string Uploadfile()
{
string msg = "";
try
{
HttpPostedFile file = HttpContext.Current.Request.Files["file"];
string saveFile = file.FileName;
//code to save the file
msg = "File uploaded";
}
catch (Exception ex)
{
msg = "Could not upload file: " + ex.Message;
}
return msg;
}
Please tell me where I am missing in my code...
This code works for me...
[HttpPost]
[Route("Uploadfile")]
public UploadFile Uploadfile()
{
HttpPostedFile file = HttpContext.Current.Request.Files["file"];
UploadFile uploadedfile = new UploadFile();
//HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Accepted);
try
{
if (file == null)
return uploadedfile ;
//response = Request.CreateResponse(HttpStatusCode.NotFound, "");
int count; int sum = 0;
byte[] buffer = new byte[file.ContentLength];
int length = (int)file.InputStream.Length;
buffer = new byte[length];
while ((count = file.InputStream.Read(buffer, sum, length - sum)) > 0)
sum += count;
FileVM fileObj = new FileVM();
NameValueCollection parameters = HttpContext.Current.Request.Params;
if (parameters.Keys.Count > 0)
{
fileObj.fileId = "";
fileObj.fileName = file.FileName.ToString();
fileObj.fileType = file.ContentType;
fileObj.filedata = "";
fileObj.LastDownLoad = parameters.GetValues("LastDownLoad")[0];
ServicecltClients srv = new ServicecltClients();
uploadedfile.FileId = srv.InsertDocumentAndRelatedClient(fileObj, buffer);
uploadedfile.FileType = fileObj.fileType;
//response = Request.CreateResponse<UploadFile>(HttpStatusCode.OK, uploadedfile);
}
}
catch (Exception _ex)
{
//response = Request.CreateResponse(HttpStatusCode.InternalServerError, _ex.Message);
ErrorLog.TraceErrorLog(_ex);
}
finally
{
file.InputStream.Close();
}
return uploadedfile;
}

500 internal server error when writing file to the server

I'm developing an android app with Xamarin that uploads file to the server. My server is asp.net based and is hosted by azure. Xamarin throws this error when the code tries to write the file to the server directory. The code I'm using to post the file to the server is as follows:
public async Task<HttpResponseMessage> UploadFile(byte[] file)
{
videoThumbName = Guid.NewGuid().ToString();
var progress = new System.Net.Http.Handlers.ProgressMessageHandler();
progress.HttpSendProgress += progress_HttpSendProgress;
using (var client = HttpClientFactory.Create(progress))
{
client.BaseAddress = new Uri(GlobalVariables.host);
// Set the Accept header for BSON.
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/bson"));
var request = new uploadFileModel { data = file, dateCreated = DateTime.Now, fileName = fileName, username = loggedUser, VideoThumbName = videoThumbName};
// POST using the BSON formatter.
MediaTypeFormatter bsonFormatter = new BsonMediaTypeFormatter();
var m = client.MaxResponseContentBufferSize;
var result = await client.PostAsync("api/media/upload", request, bsonFormatter);
return result.EnsureSuccessStatusCode();
}
}
I've tried using a try catch block and the weird thing is that the exception is caught even after the file has been written to the path and I get the 500 internal server error. So far every file I tried to upload was save to the path but I can't figure out why is error occurring.
My server side code looks like the following:
[HttpPost]
[Route("upload")]
public async Task<HttpResponseMessage> Upload(uploadFileModel model)
{
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (ModelState.IsValid)
{
string thumbname = "";
string resizedthumbname = Guid.NewGuid() + "_yt.jpg";
string FfmpegPath = Encoding_Settings.FFMPEGPATH;
string tempFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/tempuploads"), model.fileName);
string pathToFiles = HttpContext.Current.Server.MapPath("~/tempuploads");
string pathToThumbs = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/thumbs");
string finalPath = HttpContext.Current.Server.MapPath("~/contents/member/" + model.username + "/flv");
string resizedthumb = Path.Combine(pathToThumbs, resizedthumbname);
var outputPathVid = new MediaFile { Filename = Path.Combine(finalPath, model.fileName) };
var inputPathVid = new MediaFile { Filename = Path.Combine(pathToFiles, model.fileName) };
int maxWidth = 380;
int maxHeight = 360;
var namewithoutext = Path.GetFileNameWithoutExtension(Path.Combine(pathToFiles, model.fileName));
thumbname = model.VideoThumbName;
string oldthumbpath = Path.Combine(pathToThumbs, thumbname);
var fileName = model.fileName;
try
{
File.WriteAllBytes(tempFilePath, model.data);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
if (model.fileName.Contains("audio"))
{
File.WriteAllBytes(Path.Combine(finalPath, model.fileName), model.data);
string audio_thumb = "mic_thumb.jpg";
string destination = Path.Combine(pathToThumbs, audio_thumb);
string source = Path.Combine(pathToFiles, audio_thumb);
if (!System.IO.File.Exists(destination))
{
System.IO.File.Copy(source, destination, true);
}
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = "mic_thumb.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
long videoid = VideoBLL.Process_Info(vd, false);
}
The exception doesn't reveal much for me to understand the issue. Strangely I don't get any errors when I'm sending request to the local server. Any idea what might be wrong here?
Edit:
The exception no longer occurring when I get the internal server error at this line of my code using (var engine = new Engine()) This is a library I'm trying to use to encode a media file. If everything works on the local server then why doesn't it on the live server :/
using (var engine = new Engine())
{
engine.GetMetadata(inputPathVid);
// Saves the frame located on the 15th second of the video.
var outputPathThumb = new MediaFile { Filename = Path.Combine(pathToThumbs, thumbname+".jpg") };
var options = new ConversionOptions { Seek = TimeSpan.FromSeconds(0), CustomHeight = 360, CustomWidth = 380 };
engine.GetThumbnail(inputPathVid, outputPathThumb, options);
}
Image image = Image.FromFile(Path.Combine(pathToThumbs, thumbname+".jpg"));
//var ratioX = (double)maxWidth / image.Width;
//var ratioY = (double)maxHeight / image.Height;
//var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(maxWidth);
var newHeight = (int)(maxHeight);
var newImage = new Bitmap(newWidth, newHeight);
Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
Bitmap bmp = new Bitmap(newImage);
bmp.Save(Path.Combine(pathToThumbs, thumbname+"_resized.jpg"));
//File.Delete(Path.Combine(pathToThumbs, thumbname));
using (var engine = new Engine())
{
var conversionOptions = new ConversionOptions
{
VideoSize = VideoSize.Hd720,
AudioSampleRate = AudioSampleRate.Hz44100,
VideoAspectRatio = VideoAspectRatio.Default
};
engine.GetMetadata(inputPathVid);
engine.Convert(inputPathVid, outputPathVid, conversionOptions);
}
File.Delete(tempFilePath);
Video_Struct vd = new Video_Struct();
vd.CategoryID = 0; // store categoryname or term instead of category id
vd.Categories = "";
vd.UserName = model.username;
vd.Title = "";
vd.Description = "";
vd.Tags = "";
vd.Duration = inputPathVid.Metadata.Duration.ToString();
vd.Duration_Sec = Convert.ToInt32(inputPathVid.Metadata.Duration.Seconds.ToString());
vd.OriginalVideoFileName = model.fileName;
vd.VideoFileName = model.fileName;
vd.ThumbFileName = thumbname+"_resized.jpg";
vd.isPrivate = 0;
vd.AuthKey = "";
vd.isEnabled = 1;
vd.Response_VideoID = 0; // video responses
vd.isResponse = 0;
vd.isPublished = 1;
vd.isReviewed = 1;
vd.Thumb_Url = "none";
//vd.FLV_Url = flv_url;
vd.Embed_Script = "";
vd.isExternal = 0; // website own video, 1: embed video
vd.Type = 0;
vd.YoutubeID = "";
vd.isTagsreViewed = 1;
vd.Mode = 0; // filter videos based on website sections
//vd.ContentLength = f_contentlength;
vd.GalleryID = 0;
long videoid = VideoBLL.Process_Info(vd, false);
}`enter code here`

Best method to send image and a text from android to wcf service

I need to send an image and text from android to wcf service, tried with http client with multipart but no luck, kindly suggest.
send image using multipartBuilder and send text separately as json via http url connection, the below code for sending image to wcf service is this
Android code
public String postFiless( byte[] imgbyt, String urlString) throws Exception {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
byte[] data = imgbyt;
String fileName = String.format("File_%d.jpg",new Date().getTime());
ByteArrayBody bab = new ByteArrayBody(data, fileName);
builder.addPart("image", bab);
final HttpEntity entity = builder.build();
post.setEntity(entity );
HttpResponse response = client.execute(post);
Log.e("result code", ""+response.getStatusLine().getStatusCode());
return getContent(response);
}
public static String getContent(HttpResponse response) throws IOException {
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String body = "";
String content = "";
while ((body = rd.readLine()) != null)
{
content += body + "\n";
}
return content.trim();
}
WCF CODE TO GET THE IMAGE STREAM SENT FROM ANDROID
Three steps to upload image using Multipart Parser from android to WCF Rest Service
//Step 1
//WCF Rest Interface
// Namespace
using System.IO;
[OperationContract]
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, UriTemplate = "/UploadImg")]
string UploadImg(Stream fileStream);
Step 2
// WCF Implementation class
// Name spaces
using System.IO;
public string UploadImg(Stream fileStream) {
string strRet = string.Empty;
string strFileName = AppDomain.CurrentDomain.BaseDirectory + "Log\\"; // System.Web.Hosting.HostingEnvironment.MapPath("~/Logs/");
string Path = HttpContext.Current.Server.MapPath("~/Photos");// System.Web.Hosting.HostingEnvironment.MapPath("~/Photos/");// HttpContext.Current.Server.MapPath("~/Photos/")
try {
MultipartParser parser = new MultipartParser(fileStream);
if (parser.Success) {
string fileName = parser.Filename;
string contentType = parser.ContentType;
byte[] fileContent = parser.FileContents;
Encoding encoding = Encoding.UTF8;
FileStream fileToupload = new FileStream(Path + "/" + fileName, FileMode.Create);
fileToupload.Write(fileContent, 0, fileContent.Length);
fileToupload.Close();
fileToupload.Dispose();
fileStream.Close();
strRet= fileName;
} else {
return "Image Not Uploaded";
} }
catch (Exception ex) {
// handle the error
}
return strRet;
}
Step 3
// MultipartParser class
//Namespace
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
public class MultipartParser {
public IDictionary<string, string> Parameters = new Dictionary<string, string>();
public MultipartParser(Stream stream) {
this.Parse(stream, Encoding.UTF8);
}
public MultipartParser(Stream stream, Encoding encoding) {
this.Parse(stream, encoding);
}
public string getcontent(Stream stream, Encoding encoding) {
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
string[] sections = content.Split(new string[] { delimiter }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in sections) {
Match nameMatch = new Regex(#"(?<=name\=\"")(.*?)(?=\"")").Match(s);
string name = nameMatch.Value.Trim().ToLower();
if (!string.IsNullOrWhiteSpace(name)) {
int startIndex = nameMatch.Index + nameMatch.Length + "\r\n\r\n".Length;
}
}
string strRet = ""; //Parameters["name"];
return strRet;
}
private void Parse(Stream stream, Encoding encoding) {
this.Success = false;
// Read the stream into a byte array
byte[] data = ToByteArray(stream);
// Copy to a string for header parsing
string content = encoding.GetString(data);
// The first line should contain the delimiter
int delimiterEndIndex = content.IndexOf("\r\n");
if (delimiterEndIndex > -1) {
string delimiter = content.Substring(0, content.IndexOf("\r\n"));
// Look for Content-Type
Regex re = new Regex(#"(?<=Content\-Type:)(.*?)(?=\r\n\r\n)");
Match contentTypeMatch = re.Match(content);
// Look for filename
re = new Regex(#"(?<=filename\=\"")(.*?)(?=\"")");
Match filenameMatch = re.Match(content);
//re = new Regex(#"(?<=name\=\"")(.*?)(?=\"")");
//Match nameMatch = re.Match(content);
// Did we find the required values?
if (contentTypeMatch.Success && filenameMatch.Success) {
// Set properties
this.ContentType = contentTypeMatch.Value.Trim();
this.Filename = filenameMatch.Value.Trim();
// Get the start & end indexes of the file contents
int startIndex = contentTypeMatch.Index + contentTypeMatch.Length + "\r\n\r\n".Length;
byte[] delimiterBytes = encoding.GetBytes("\r\n" + delimiter);
int endIndex = IndexOf(data, delimiterBytes, startIndex);
int contentLength = endIndex - startIndex;
// Extract the file contents from the byte array
byte[] fileData = new byte[contentLength];
Buffer.BlockCopy(data, startIndex, fileData, 0, contentLength);
this.FileContents = fileData;
this.Success = true; }
} }
private int IndexOf(byte[] searchWithin, byte[] serachFor, int startIndex) {
int index = 0;
int startPos = Array.IndexOf(searchWithin, serachFor[0], startIndex);
if (startPos != -1) {
while ((startPos + index) < searchWithin.Length) {
if (searchWithin[startPos + index] == serachFor[index]) {
index++;
if (index == serachFor.Length) {
return startPos;
}
} else {
startPos = Array.IndexOf<byte>(searchWithin, serachFor[0], startPos + index);
if (startPos == -1) {
return -1;
}
index = 0;
}
}
}
return -1;
}
private byte[] ToByteArray(Stream stream) {
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream()) {
while (true) {
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
}
public bool Success {
get;
private set;
}
public string ContentType {
get;
private set;
}
public string Filename {
get;
private set;
}
public byte[] FileContents {
get;
private set;
}
public string Imgname {
get;
private set;
} }
// End of Wcf rest Service Code

How to get Metadata of an object retrieved from amazon S3 in android?

I am retrieving an object from amazon s3.How to get metadata of retrieved object in android? From the metadata, i want to find out whether that object is image or Non-image (like pdf, csv, ...)
Thanks for any help.
I am using the following code for getting list of names under a folder.
AmazonS3Client s3Client;
s3Client = new AmazonS3Client(new BasicAWSCredentials(
Constants.ACCESS_KEY_ID, Constants.SECRET_KEY));
ObjectListing objListOfPath = s3Client.listObjects(
Constants.getPictureBucket(), path);
List<S3ObjectSummary> keyListOfObjectSummaries = objListOfPath
.getObjectSummaries();
ObjectListing next = s3Client.listNextBatchOfObjects(objListOfPath);
keyListOfObjectSummaries.addAll(next.getObjectSummaries());
System.out.println("keyListOfObjectSummaries size() "
+ keyListOfObjectSummaries.size());
ArrayList<String> arrListImageName = new ArrayList<String>();
if (keyListOfObjectSummaries.size() > 0) {
for (int i = 0; i < keyListOfObjectSummaries.size(); i++) {
String imagePath = keyListOfObjectSummaries.get(i).getKey();
arrListImageName.add(strImageName);
}
for (int i = 0; i < arrListImageName.size(); i++) {
System.out.println("Index " + i + " image Name "
+ arrListImageName.get(i));
String strReceiptImageName = arrListImageName.get(i);
String strReceiptNameExtension = extractReceiptNameExtension(arrListImageName.get(i));
S3Object objectReceiptFromAmazonS3 = s3Client.getObject(
Constants.PICTURE_BUCKET, keyListOfObjectSummaries
.get(i).getKey());
InputStream inputStreamReceiptObject = objectReceiptFromAmazonS3
.getObjectContent();
SOLUTION:
System.out.println("CONTENT TYPE " +objectReceiptFromAmazonS3.getObjectMetadata().getContentType());
Thanks to Harshit and sanket !
This has worked for me to download a file hosted in S3 from a simple servlet.
private static final int BYTES_DOWNLOAD = 1024;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String key = request.getParameter("key");
HttpSession session = request.getSession();
String bucketname = (String) session.getAttribute("BUCKETNAME");
AmazonS3 s3 = new AmazonS3Client(Constants.credentials);
Region usWest2 = Region.getRegion(Regions.US_WEST_2);
s3.setRegion(usWest2);
S3Object object = s3.getObject(new GetObjectRequest(bucketname, key));
response.setContentType(object.getObjectMetadata().getContentType());
response.setHeader("Content-Disposition","attachment;filename="+object.getKey());
InputStream is = object.getObjectContent();int read=0;
byte[] bytes = new byte[BYTES_DOWNLOAD];
OutputStream os = response.getOutputStream();
while((read = is.read(bytes))!= -1){
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
use this couple of lines :
ObjectMetadata metaData = new ObjectMetadata();
metaData.addUserMetadata("key", key of your file);
System.out.println("Content type is========"+metaData.getContentType());
this might be help you..

Categories

Resources