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`
Related
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;
}
}
}
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);
}
}
I'm uploading a file in my Android application. The code is pretty simple:
private boolean UploadFile(String fileLocation) {
try {
if (TextUtils.isEmpty(fileLocation)) {
return false;
}
File fSrc = new File(fileLocation);
if (!fSrc.exists()) {
return false;
}
boolean bReturn = AzureManager.init(this);
if (!bReturn) {
return false;
}
String blobName = fSrc.getName();
InputStream in = new BufferedInputStream(new FileInputStream(fSrc));
CloudBlobContainer container = AzureManager.getCloudBlobClient().getContainerReference(AzureManager.getContainerName());
CloudBlockBlob blob = container.getBlockBlobReference(blobName);
blob.upload(in, fSrc.length());
in.close();
return true;
} catch (Exception e) {
//handle exception
}
return false;
}
When I download from Azure, CloudBlockBlob has a download listener as:
blob.setDownloadListener(eventListener);
But how can I keep track of the progress when uploading?
I am also finding for the way to do it in Java or Android. But, if you want to make it by your own way, without changing anything on server, you can make it similar to this answer. The answer is in C# so you need to find similar method for Java library and update it accordingly.
If you don't want to go on that answer, you can refer the same code from here as well.
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static CloudStorageAccount storageAccount = new CloudStorageAccount(new StorageCredentials("accountname", "accountkey"), true);
static void Main(string[] args)
{
CloudBlobClient myBlobClient = storageAccount.CreateCloudBlobClient();
myBlobClient.SingleBlobUploadThresholdInBytes = 1024 * 1024;
CloudBlobContainer container = myBlobClient.GetContainerReference("adokontajnerneki");
//container.CreateIfNotExists();
CloudBlockBlob myBlob = container.GetBlockBlobReference("cfx.zip");
var blockSize = 256 * 1024;
myBlob.StreamWriteSizeInBytes = blockSize;
var fileName = #"D:\cfx.zip";
long bytesToUpload = (new FileInfo(fileName)).Length;
long fileSize = bytesToUpload;
if (bytesToUpload < blockSize)
{
CancellationToken ca = new CancellationToken();
var ado = myBlob.UploadFromFileAsync(fileName, FileMode.Open, ca);
Console.WriteLine(ado.Status); //Does Not Help Much
ado.ContinueWith(t =>
{
Console.WriteLine("Status = " + t.Status);
Console.WriteLine("It is over"); //this is working OK
});
}
else
{
List<string> blockIds = new List<string>();
int index = 1;
long startPosition = 0;
long bytesUploaded = 0;
do
{
var bytesToRead = Math.Min(blockSize, bytesToUpload);
var blobContents = new byte[bytesToRead];
using (FileStream fs = new FileStream(fileName, FileMode.Open))
{
fs.Position = startPosition;
fs.Read(blobContents, 0, (int)bytesToRead);
}
ManualResetEvent mre = new ManualResetEvent(false);
var blockId = Convert.ToBase64String(Encoding.UTF8.GetBytes(index.ToString("d6")));
Console.WriteLine("Now uploading block # " + index.ToString("d6"));
blockIds.Add(blockId);
var ado = myBlob.PutBlockAsync(blockId, new MemoryStream(blobContents), null);
ado.ContinueWith(t =>
{
bytesUploaded += bytesToRead;
bytesToUpload -= bytesToRead;
startPosition += bytesToRead;
index++;
double percentComplete = (double)bytesUploaded / (double)fileSize;
Console.WriteLine("Percent complete = " + percentComplete.ToString("P"));
mre.Set();
});
mre.WaitOne();
}
while (bytesToUpload > 0);
Console.WriteLine("Now committing block list");
var pbl = myBlob.PutBlockListAsync(blockIds);
pbl.ContinueWith(t =>
{
Console.WriteLine("Blob uploaded completely.");
});
}
Console.ReadKey();
}
}
}
I'm developing an app in FlashDevelop, using Haxe and OpenFl
When I test my app in flash target, it works fine. But when I compile for android, it comes up with this error during the compilation:
./src/ReaderView2.cpp: In member function 'virtual Void ReaderView2_obj::setZoom()':
./src/ReaderView2.cpp:653: error: base operand of '->' has non-pointer type 'String'
Build halted with errors (haxelib.exe).
...Which is obviously something to do with cpp, which I'm not really an expert.
Does any body know what the error means?
Here's the setZooom function: (the whole file is quite large)
public function setZoom()
{
hideOptions();
while (numChildren > 0)
{
Main.remove(getChildAt(0));
}
if (image != null) if (image.parent != null) image.parent.removeChild(image);
images = new Array();
field = new TextField();
var fieldFont = Assets.getFont("fonts/Kreon-Regular.ttf");
var format:TextFormat = new TextFormat(fieldFont.fontName, currentZoom, 0x4F4F4F);
format.align = TextFormatAlign.LEFT;
field.defaultTextFormat = format;
field.embedFonts = true;
field.text = fullText;
field.selectable = false;
field.wordWrap = true;
field.border = false;
field.autoSize = TextFieldAutoSize.LEFT;
field.width = displayWidth;
//field.x = 0;
//split string into words
var allParas:Array<String> = fullText.split("\r\n");
var words:Array<String>;
var fields:Array<TextField> = new Array();
var tempField:TextField = null;
var contentHeight:Float = displayHeight;
var wordI:Int;
var paraI:Int = 0;
var tempArr2:Array<String>;
while (paraI < allParas.length)
{
if (false) //check img tag
{
}
else //if para is words
{
wordI = 0;
words = allParas[paraI].split(" ");
while (wordI < words.length)
{
if (tempField == null || tempField.textHeight > contentHeight)
{
if (tempField != null) {
wordI--;
tempArr2 = tempField.text.toString().split(" ");
for (i in 0... tempArr2.length)
{
tempArr2.remove("");
}
tempArr2.pop();
tempField.text = tempArr2.join(" ");
}
tempField = new TextField();
tempField.defaultTextFormat = field.getTextFormat();
tempField.embedFonts = true;
tempField.text = "";
tempField.border = false;
tempField.selectable = false;
tempField.wordWrap = true;
tempField.autoSize = TextFieldAutoSize.LEFT;
tempField.width = displayWidth-2;
tempField.x = 0;
fields.push(tempField);
}
else
{
tempField.appendText(words[wordI] + (wordI == words.length - 1? "\n": " "));
wordI++;
}
}
}
paraI++;
}
var bd:BitmapData;
for (i in 0... fields.length)
{
bd = new BitmapData(Std.int(fields[i].width), Std.int(fields[i].height));
bd.draw(fields[i]);
images.push(new Bitmap(bd, PixelSnapping.AUTO, true));
}
//addChild(fields[0]);
images[0].x = 10;
addChild(images[0]);
currentPageInstance = images[0];
currentPage = 0;
drawScrollBar();
if (optionsBtn!=null)addChild(optionsBtn);
}
So apparently using the toString() funcion gives problems for a cpp target.
I got an error when using phonegap FileTransfer upload and webservice asmx
Here is the code for phonegap
function uploadNow(){
//alert(imgURI);
var options = new FileUploadOptions();
options.fileKey = "file";
//options.fileName = imgURI.substr(imgURI.lastIndexOf('/') + 1);
options.fileName = "face-275.jpg";
options.mimeType = "image/jpeg";
//alert(options.fileName);
var params = new Object();
params.value1 = "test";
params.value2 = "param";
options.params = params;
var ft = new FileTransfer();
ft.upload("file:///mnt/sdcard/Merabu Survey/Picture/face-275.jpg",
"http://192.168.0.231/mservice/MainService.asmx/UploadService",
win, fail, options);
And here is my asmx code
[WebMethod]
public string UploadService()
{
//string rootPathRemote = ConfigurationManager.AppSettings["UploadedFilesPath"].TrimEnd('/', '\\') + "/";
//string rootPhysicalPathRemote = rootPathRemote + "\\";
int fileCount = 0;
fileCount = HttpContext.Current.Request.Files.Count;
for (int i = 0; i < fileCount; i++)
{
HttpPostedFile file = HttpContext.Current.Request.Files[i];
string fileName = HttpContext.Current.Request.Files[i].FileName;
if (!fileName.EndsWith(".jpg"))
{
fileName += ".jpg";
}
string sourceFilePath = Path.Combine("F:\\Live Website\\upload", fileName);
file.SaveAs(sourceFilePath);
}
return "test";
}
I got an error for http status 500 and error code 1 from my adb log chat.
i already add my webservice domain to whitelist.
Anyone know how to solve this?