I'm developing a Universal App for Windows Phone 8.1 but I'm using a PHP Page to get recognize some patterns from an Image that I uploaded to my service.
I have discovered that after I uploaded X image to Azure, I cannot use it. I'm using WebMatrix to develop my PHP Page and when I refresh it, it doesn't show me the images that I uploaded however when I try to publish something and I select the option: "Delete files on the remote server that are not on my computer." I can see my images. This is an example of my PHP code:
$uploaddir = getcwd();
$uploadfile = $uploaddir . "/" . basename($_FILES['userfile']['name']);
if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
chmod($uploadfile, 0755);
$Test = new Display($_FILES['userfile']['name']);
echo '{"result": "' . $Test->getNumber($_REQUEST['color'], false) . '"}';
//unlink($uploadfile);
} else {
echo '{"result": "-1"}';
}
I'd like to know what could be my bug because I don't understand why I can access from the URL, too to the bit I cannot use it, maybe it's how I assigned the permissions but with or without the chmod, it doesn't change at all. I have even tried other hostings and the problem is the same when I enter the File Manager, there are only my PHP files and it doesn't allow me to manage the image.
This is my Windows Phone code to upload the Image if it's necessary:
byte[] ConvertBitmapToByteArray()
{
WriteableBitmap bmp = bitmap;
using (Stream stream = bmp.PixelBuffer.AsStream())
{
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
return memoryStream.ToArray();
}
}
public async Task<string> Upload()
{
try
{
using (var client = new HttpClient())
{
using (var content =
new MultipartFormDataContent())
{
byte[] data = ConvertBitmapToByteArray();
using (var stream = new InMemoryRandomAccessStream())
{
// encoder *outputs* to stream
var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.BmpEncoderId, stream);
// encoder's input is the bitmap's pixel data
encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Straight,
(uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, data);
await encoder.FlushAsync();
content.Add(new StreamContent(stream.AsStream()), "userfile", fileNewImage);
using (
var message =
await client.PostAsync("http://xplace.com/uploadtest.php", content))
{
var input = await message.Content.ReadAsStringAsync();
return input;
}
}
}
}
}
catch (Exception ex)
{
return null;
}
}
Thanks for your worthy knowledge and experience.
Create a blob storage account, and add a public container. In your action to save the file, store the file in you blob storage container. Then you can access the image as you would with any other image.
Here is a tutorial on Azure: http://azure.microsoft.com/en-us/documentation/articles/storage-dotnet-how-to-use-blobs/
Also, you cannot create folders in a container, but you could use a naming convention on the blobrefname to create the idea of a container. Also, you can attach a domain to the cloud service if you want the URL to have a certain look.
READ YOUR QUESTION AGAIN - And it looks like it's more on the client side.
Here is what I usually do to attach a file to a MultipartFormDataContent:
MultipartFormDataContent content = new MultipartFormDataContent();
FileInfo info = new FileInfo(currFileLoc);
string contentMediaType = null;
//This is a Dictionary<string, string> that takes in the file
//extension, and returns the media type (e.g. "image/jpeg")
GlobalVariables.ApprovedMediaTypes.TryGetValue(
info.Extension.ToLower()
, out contentMediaType);
//If the dictionary doesn't return a result
//then it's not a supported file type
if (contentMediaType == null)
throw new Exception(
String.Format("The file \"{0}\" is an unsupported file type."
, info.Name));
ByteArrayContent currFile = new ByteArrayContent(File.ReadAllByte(currFileLoc));
currFile.Headers.ContentType = new MediaTypeWithQualityHeaderValue(contentMediaType);
content.Add(currFile, currFileLoc, currFileLoc);
The I make my call. Maybe you found another option with blob storage. Finally, if you load large files, you may want to look into uploading in chunks.
Related
I'm using gridfs to store files in MongoDB. I'm facing a problem when I try to show the large pdf file in the browser, which is saved in gridfs. Large files don't show up in the browser, but small files does.
This is the service code
public function getIpFileByFileId() {
$request = $this->request;
$dm = $this->container->get('doctrine_mongodb')->getManager('patient');
$id = $request->get('fileId');
//get doc
$docIpMapping = $dm->getRepository('PatientDocumentsBundle:IPDocuments')->findOneBy([
'id' => $id
]);
$base64 = (base64_encode($docIpMapping->getFile()->getBytes()));
$response['data'] = $base64;
$response['msg'] = 'success';
return $response;
}
And this is the front end code
Ajax(path, data).success(function (result) {
$("#pdfDiv").html('<iframe style="width:100%;height:500px;" src="data:application/pdf;base64,' + result.data + '"></iframe>');
});
Does the code have any issues? How do I display large files in the front end?
Here is my suggestion, without open in new tab,
http://answerexpress.blogspot.com/2018/09/show-preview-of-pdf-file-saved-in.html
I am new to the Facebook Marketing API and what I am working on is to upload an image to my FB Marketing library.
Right now, I can successfully upload an image to the FB Marketing but unfortunately I cannot see if there is a way to upload an image from a URL.
Has anyone had any previous experience with that ?
Code sample:
Api::init(getenv('FACEBOOK_APP_ID'), getenv('FACEBOOK_APP_SECRET'), getenv('FACEBOOK_APP_TOKEN'));
/**
* {#inheritdoc}
*/
public function testFunc()
{
$adAccountId = getenv('FACEBOOK_APP_ACCOUNT_ID');
$account = new AdAccount();
$account->{AdAccountFields::ID} = $adAccountId;
$image = new AdImage(null, "act_{$account->id}");
$image->{AdImageFields::FILENAME} = getenv('FACEBOOK_APP_MARKETING_PATH').'fbTestImage.png';
$image->create();
$this->line('Image Hash: '.$image->{AdImageFields::HASH}.PHP_EOL);
}
You have to use PHP to pull the image from the URL write it to a temporary file, upload. that then delete the temporary file when complete (Not ideal but a solution). The the Node.js Marketing API you can supply the content rather than the filename to the API which is nice.
However a possible solution for now.
$url = "https://www.sample/image.png";
// Create output file name
$arr = explode("/",$url);
$img_file = dir(__FILE__).'/tmp_'.$arr[count($arr)-1];
// Load File contents from URL
$data = file_get_contents($url);
// Write Temporary File
$fp = fopen($img_file,"w");
fwrite($fp,$data);
fclose($fp);
// Then Push the temp file to Facebook
// Rest of FB Code...
$image->{AdImageFields::FILENAME} = $img_file;
// Wait for the Upload to complete then delete the temp file
unlink($img_file);
I think I'm losing my mind. I can't seem to find out how to rename a blob using the azure-storage-php SDK located here: https://github.com/Azure/azure-storage-php
This is my current code:
$blobListOptions = new ListBlobsOptions();
$blobListOptions->setPrefix($path);
// List blobs by key.
$blob_list = $blobClient->listBlobs($container, $blobListOptions);
$blobs = $blob_list->getBlobs();
if (count($blobs) > 0) {
// Only expecting one blob in this path, but looping through regardless.
foreach($blobs as $blob) {
$blob->setName($path . 'NEWNAME');
}
}
Looking at the source code, I can tell that using setName doesn't really do anything at all.
There has to be some method of doing this with the SDK without relying on the REST API.
Currently, there is no rename function we can directly use. But we can rename the blob by copying to the new name, then delete the source item.
foreach($blobs as $blob) {
$blobClient->copyBlob($container, $path . 'NEWNAME', $container, $blob->getName());
$blobClient->deleteBlob($container, $blob->getName());
}
My android app needs to fetch some info from a php server that hosts a MySQL database. It works fine so far. The server encodes the info into JSON and sends it and then I can parse it well.
But now I need to also fetch an image together with each row of info I get from the DB. The info I'm getting has a field where it specifies the path where the correspondent image is located in the filesystem.
So, once I get the paths of the images, how do I read them so that I can send them together with the info rows obtained? Can I JSON encode the images together with the info? Or should I read them one by one with readfile once I have the info in the android app? If it can be done with JSON, how do you parse the data of the image afterwards? Can you provide an example?
One way to get an image in textform would be to use base64. I have used it with several webservices and there is decoders for Android out there, actually. There is one in the source code since API level 8. http://developer.android.com/reference/android/util/Base64.html but since I want to target other levels I include it myself.
One easy way would then be to save the image in a database instead as a file.
This is what I did to fetch the images together with the data. I post it so that if it can help someone.
This is the part of the PHP script that sends the data in the server side:
$i=0;
//$sql contains the result from the query of the data
while($row=mysql_fetch_array($sql)){
$output[]=$row;
//Here we fetch the image from the files table
$query = "SELECT path, type FROM FILES WHERE poi_id = '" . mysql_real_escape_string(trim($output[$i][0])) . "'";
$r = mysql_query($query);
$img = mysql_fetch_array($r);
$bin = base64_encode_image($img[0]);
//Let's append the image and the type to the data output.
$output[$i]['img'] = $bin;
$output[$i]['type'] = $img[1];
$i++;
}
//This method sends the response to the Android app
//You can just use echo(json_encode($output));
RestUtils::sendResponse(200, json_encode($output), 'application/json');
And then in the Android app, after parsing the JSON, you can save the base64 string as an image to the file system like this:
public void createImage(String image, String name){
try{
byte[] imageAsBytes = Base64.decode(image.getBytes(), Base64.DEFAULT);
Bitmap img_bitmap = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
FileOutputStream fos = openFileOutput(name, Context.MODE_WORLD_READABLE);
img_bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
}
catch(Exception e){
e.printStackTrace();
}
}
for downloading image from path
public void DownloadImageFromPath(String path){
InputStream in =null;
Bitmap bmp=null;
ImageView iv = (ImageView)findViewById(R.id.img1);
int responseCode = -1;
try{
URL url = new URL(path);//"http://192.xx.xx.xx/mypath/img1.jpg
HttpURLConnection con = (HttpURLConnection)url.openConnection();
con.setDoInput(true);
con.connect();
responseCode = con.getResponseCode();
if(responseCode == HttpURLConnection.HTTP_OK)
{
//download
in = con.getInputStream();
bmp = BitmapFactory.decodeStream(in);
in.close();
iv.setImageBitmap(bmp);
}
}
catch(Exception ex){
Log.e("Exception",ex.toString());
}
}
I am trying to upload image files to my server using AS3 and PHP, and at the moment I am succeeding in uploading multiple files and restricting it to images only, but since I am new to Flash and AS3, I am finding it difficult to figure out how to have a loader bar show when the files are being uploaded, as well as executing a function once all files have been uploaded to go to a specified frame.
Here is my code thus far,
AS3:
import flash.net.FileReferenceList;
import flash.events.Event;
import flash.net.URLRequest;
import flash.net.FileReference;
var fileRef:FileReferenceList = new FileReferenceList();
fileRef = new FileReferenceList();
fileRef.browse(new Array( new FileFilter( "Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png" )));
fileRef.addEventListener(Event.SELECT, fileSelectHandler);
var uploadURL:URLRequest = new URLRequest();
var uploadPhotoScript:String = "http://127.0.0.1/upload.php";
uploadURL.url = uploadPhotoScript;
function fileSelectHandler(event:Event):void {
for each(var fileToUpload:FileReference in fileRef.fileList){
uploadSingleFile(fileToUpload);
}
}
function uploadSingleFile(file:FileReference):void {
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function completeHandler(event:Event):void {
trace("upload complete");
}
PHP:
if(!empty($_FILES)){
$tmpfile = $_FILES['Filedata']['tmp_name'];
$targetfile = dirname(__FILE__) . '/' . $_FILES['Filedata']['name'];
move_uploaded_file($tmpfile, $targetfile);
}
my questions are,
1: how can I display a percentage or a uploading bar indicating the progress of the files being uploaded?
2: How can I launch a callback function after ALL files have been uploaded successfully?
3: How can I make the file browser appear on click, and not upon loading the flash file?
If you guys could post a link or two to good tutorials/resources or some advice, maybe even a code snippet or two that would be a great help as I am very new to Actionscript 3.
Thanx in advance!
To answer your questions in sequence:
1: You can use the ProgressEvent to display file upload progress. Since the File will be the dispatcher of the event, you can access the FileReference that has dispatched the progress as e.currentTarget inside the event, and from here you can access the unique properties of that file reference so you can accurately update the visual upload progress for that specific file. For example:
function uploadSingleFile(file:FileReference):void {
file.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function onUploadProgress(e:ProgressEvent):void
{
var f:FileReference = e.currentTarget as FileReference;
var fileName:String = f.name; //Now I know which file it is, I can update accordingly
var progress:Number = (e.bytesLoaded / e.bytesTotal) * 100; //shows percent, you might want to round this off using Math.round(number);
}
2: In order to launch a callback after ALL files are loaded, you'd do this by storing the number of files initially selected, then adding a callback specifically to each item and as they complete, decrement the total count until it is 0, at which time you'll know all files have been uploaded:
var totalFiles:int = 0;
function fileSelectHandler(event:Event):void {
for each(var fileToUpload:FileReference in fileRef.fileList){
++totalFiles;
uploadSingleFile(fileToUpload);
}
}
function uploadSingleFile(file:FileReference):void {
file.addEventListener(ProgressEvent.PROGRESS, onUploadProgress);
file.addEventListener(Event.COMPLETE, onFileUploadComplete);
file.upload(uploadURL);
file.addEventListener(Event.COMPLETE, completeHandler);
}
function onFileUploadComplete(e:Event):void
{
--totalFiles;
if(totalFiles == 0){
//All files have been uploaded
}
}
3: To make the browser appear onClick, simply add a MouseEvent.MOUSE_DOWN listener to an object or button of some kind, or even the stage, whatever. Like so:
var uploadButton:Button = new Button(); // Note this will require the Button component to be included in your library in flash CS
uploadButton.label = "Upload Files";
uploadButton.width = 150; //Or whatever;
uploadButton.x = (stage.stageWidth * .5) - (uploadButton.width * .5);
uploadButton.y = (stage.stageHeight * .5) - (uploadButton.height * .5);
stage.addChild(uploadButton);
uploadButton.addEventListener(MouseEvent.MOUSE_DOWN, onUploadClicked);
function onUploadClicked(e:MouseEvent):void
{
var fileRef:FileReferenceList = new FileReferenceList();
fileRef = new FileReferenceList();
fileRef.browse(new Array( new FileFilter( "Images (*.jpg, *.jpeg, *.gif, *.png)", "*.jpg;*.jpeg;*.gif;*.png" )));
fileRef.addEventListener(Event.SELECT, fileSelectHandler);
}
And finally about the tutorials etc, I'd recommend http://gotoandlearn.com for learning flash. I would also recommend just checking out the AS3 docs, as all of this nfo can be gleaned from just looking up the class in question, FileReferenceList. Please note I've done this code off of the top of my head in here so I had no IDE checking or anything. However it should work just fine. Hope this helps. :)
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReferenceList.html
http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/FileReference.html#upload()
http://adobe.com/go/as3lr