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();
}
}
}
Related
I created a server/client game in visual studio. The apps connect over TCP. After everything worked as intended i created the client app in Unity. When i play the game in Unity application everything is ok (The client communicates with server etc). When i export the game in Windows the game is ok. The problem is when i export it to an Android (apk) the game on the device does not communicate with server.
Using Debugger i found the first problem (not sure if there are more) is when i am trying to compress and split the package to be send. I split each package at 1024 and rejoin them at the recipient.
The pack class:
public class MessageBoxPack
{
private List<MessageBox> msgBoxContainer;
private byte[] msgByte { get; set; }
private MessageBox msgBox;
private int bufferSize;
public List<MessageBox> PrepareMsgBoxList(MessageSlip msg, int _bufferSize)
{
msgBoxContainer = new List<MessageBox>();
bufferSize = _bufferSize;
ConvertMessageToBytes(msg);
return msgBoxContainer;
}
private void ConvertMessageToBytes(MessageSlip msg)
{
BinaryFormatter f = new BinaryFormatter();
using (MemoryStream ms = new MemoryStream())
{
using (GZipStream gZip = new GZipStream(ms, CompressionMode.Compress))
{
f.Serialize(gZip, msg);
}
byte[] b = ms.ToArray();
int TotalLength = b.Length;
int currentPosition = 0;
int writeLength = bufferSize;
while (currentPosition < TotalLength)
{
msgBox = new MessageBox();
msgBox.CallBackID = msg.CallBackID;
if (currentPosition + bufferSize > TotalLength)
writeLength = TotalLength - currentPosition;
msgBox.MessageBytes = new byte[writeLength];
Array.Copy(b, currentPosition, msgBox.MessageBytes, 0, writeLength);
msgBox.currentPossition = currentPosition;
msgBox.byteLength = TotalLength;
currentPosition += writeLength;
msgBoxContainer.Add(msgBox);
}
}
}
}
And the unpack class:
public class MessageBoxUnpack
{
public MessageSlip UnpackMsgBoxList(List<MessageBox> msgBoxList, int _bufferSize)
{
MessageSlip msg = new MessageSlip();
using (MemoryStream ms = new MemoryStream())
{
foreach (MessageBox msgBox in msgBoxList)
{
//ms.Position = (int)msgBox.currentPossition;
ms.Write(msgBox.MessageBytes, 0, msgBox.MessageBytes.Length);
}
int i = (int)ms.Length;
BinaryFormatter f = new BinaryFormatter();
//ms.Flush();
ms.Position = 0;
//msg = f.Deserialize(ms) as MessageSlip;
using (GZipStream gZip = new GZipStream(ms, CompressionMode.Decompress))
{
msg = f.Deserialize(gZip) as MessageSlip;
}
}
return msg;
}
}
The Error i receive is at
using (GZipStream gZip = new GZipStream(ms, CompressionMode.Compress))
Can you explain to me where is the problem, how to correct it and let me know if the method i am using to pack, unpack and split is ok.
I am using android's thread pool executor framework (initialized as below).
BlockingQueue<Runnable> taskQueue = new LinkedBlockingQueue<>();
ExecutorService executorService = new ThreadPoolExecutor(totalCores, totalCores * 3, 10, TimeUnit.SECONDS, taskQueue);
Now, consider the following function onFrameProcessed -
public void onFrameProcessed(RenderedImage renderedImage) {
String timeNow = new SimpleDateFormat("d-M-Y_HH_mm_ss_SSS").format(new Date()).toString();
CustomRunnable3 customRunnable3 = new CustomRunnable3(renderedImage, timeNow);
executorService.execute(customRunnable3);
}
Definition of CustomRunnable3 is as follows:
class CustomRunnable3 implements Runnable {
RenderedImage renderedImageLocal;
String basePath, timeNowCopy;
int hashCode;
CustomRunnable3(RenderedImage renderedImage, String timeNow) {
renderedImageLocal = renderedImage;
this.basePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).toString();
this.timeNowCopy = timeNow;
hashCode = renderedImageLocal.hashCode();
}
#Override
public void run() {
if (renderedImageLocal.imageType() == RenderedImage.ImageType.ThermalRadiometricKelvinImage) {
int[] thermalData = renderedImageLocal.thermalPixelValues();
String dataPath = basePath + "/" + this.timeNowCopy + ".csv";
try {
PrintWriter printWriter = new PrintWriter(dataPath);
int dataLen = thermalData.length;
for (int i = 0; i < dataLen; i++) {
printWriter.println(thermalData[i]);
}
printWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
String imgPath = basePath + "/" + this.timeNowCopy + ".jpg";
try {
if (hashCode != renderedImageLocal.hashCode()) {
Log.e("Checking", "Hash code changed..");
}
renderedImageLocal.getFrame().save(new File(imgPath), frameProcessor);
if (hashCode != renderedImageLocal.hashCode()) {
Log.e("Checking", "Hash code changed after writing..");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Usage Scenario : onFrameReceived is being called multiple times per second(like 4-5 times). In each call to onFrameReceived, I am saving two files from renderedImage object (1 csv file, 1 jpg file). Both of these files must be related to each other because both are created from one parent and have same name(except the extension).
Problem : But that is not happening and somehow I am ending up with jpg file content from 1 renderedImage and csv content from another renderedImage object.
What are the possible reasons for this problem, please share your opinion.
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;
}
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`
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.