I have a blob which I've stored in Azure blob storage (using the development emulator).
Its all saved and I can see it in the server explorer in the blob store (file.mp3 if that matters).
I'm then linking to it in my site but when I click the link I'm getting a 206 (partial content) back (and obviously no file). If I right click save as everything is happy and the file downloads.
I'm sure this is something pretty noobish that I'm missing but I cant see it.
That is because, browser does not download media file as whole, browser requests Range for which Blob Storage correctly responds with one byte and with headers. This is called HTTP streaming, where parts of file will be downloaded in ranges and will be played progressively. In this form of streaming you can skip parts of file and go to end to play the end part of media without downloading whole file.
Imagine you are watching a big movie, and that movie is of 100 MB. And you want to watch last One minute of it, you can move player's tracker forward on timeline and browser will only download last few megabytes as per the timeline structure in Media file. Usually MP4 & similar media containers support file byte position tracking.
Browsers & most media players try to stream the media file if possible.
You can try following download attribute,
Reference: http://updates.html5rocks.com/2011/08/Downloading-resources-in-HTML5-a-download
download me
You can try following code, from this answer, Reference: Chrome extension: How to save a file on disk
var url = window.webkitURL || window.URL || window.mozURL || window.msURL;
var a = document.createElement('a');
a.download = 'MyHangouts-MomentCapture.jpg';
a.href = url.createObjectURL(dataURIToBlob(data.active, 'jpg'));
a.textContent = 'Click here to download!';
a.dataset.downloadurl = ['jpg', a.download, a.href].join(':');
/**
* Converts the Data Image URI to a Blob.
*
* #param {string} dataURI base64 data image URI.
* #param {string} mimetype the image mimetype.
*/
var dataURIToBlob = function(dataURI, mimetype) {
var BASE64_MARKER = ';base64,';
var base64Index = dataURI.indexOf(BASE64_MARKER) + BASE64_MARKER.length;
var base64 = dataURI.substring(base64Index);
var raw = window.atob(base64);
var rawLength = raw.length;
var uInt8Array = new Uint8Array(rawLength);
for (var i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i);
}
var bb = new this.BlobBuilder();
bb.append(uInt8Array.buffer);
return bb.getBlob(mimetype);
};
Related
I am using the CachedImage component of ffimageloading. I have a kind of gallery with a carousel view.
All the images are loaded through an internet URL, they are not local images. I would like to add the image sharing function. But I don't want to download the file again, I would like to know if there is a way to access the file that the CachedImage component already downloaded to be able to reuse it in the share function.
try using MD5Helper
var path = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey")'
Thanks Jason
I share with you how part of my code is:
var key = ImageService.Instance.Config.MD5Helper.MD5("https://yourfileUrlOrKey");
var imagePath = await ImageService.Instance.Config.DiskCache.GetFilePathAsync(key);
var tempFile = Path.Combine(Path.GetTempPath(), "test.jpg");
if (File.Exists(tempFile))
{
File.Delete(tempFile);
}
File.Copy(imagePath, tempFile);
await Share.RequestAsync(new ShareFileRequest
{
Title = "Test",
File = new ShareFile(tempFile)
});
The temporary file I believe, since the cached file has no extension and the applications do not recognize the type.
I'm working on a project that all pdf files are encrypted on Web Server.
With XMLHttpRequest I get content of the encrypted pdf file. Then with JavaScript tools I decrypt the file. After all assign the content of file to a javascript variable as decrypted_file. All this is done at client side.
Here is what i want to do;
pdf.js renders and views pdf file that is located on web server or the same directory base.
How could I handle pdf.js to get content from javascript variable not url as "http//yourdomain.com/first-test.pdf or file as "first-test.pdf"?
Any answers are welcome, thank you.
Assuming that you are using the viewer.html of PDF.js, opening a PDF file from data is as easy as calling PDFViewerApplication.open with the right parameters.
Example: Typed arrays (Uint8Array / ArrayBuffer / ..)
// in viewer.html
var data = new Uint8Array( /* ... data ... */ );
PDFViewerApplication.open(data);
Example: Blob / File objects
// in viewer.html
var data = new Blob([ '%PDF....'] , {type: 'application/pdf'});
var url = URL.createObjectURL(data);
PDFViewerApplication.open(url);
Example: data URL (if supported by browser)
var url = 'data:application/pdf;base64,....';
PDFViewerApplication.open(url);
Example: data URL (any browser)
This consists of two steps: Decoding the base64 data-URL, and then converting the binary string to an Uint8Array.
var url = 'data:application/pdf;base64,....';
var data = url.split(';base64,')[1];
// Decode base64
var binaryString = atob(data);
// Convert binary string to Uint8Array
data = new Uint8Array(binaryString.length);
for (var i = 0, ii = binaryString.length; i < ii; ++i) {
data[i] = binaryString.charCodeAt(i);
}
PDFViewerApplication.open(data);
Example: Using PDF.js in a frame
<iframe src="viewer.html" id="pdfjsframe"></iframe>
<script>
var pdfjsframe = document.getElementById('pdfjsframe');
// At the very least, wait until the frame is ready, e.g via onload.
pdfjsframe.onload = function() {
var data = ... data here or elsewhere ... ;
pdfjsframe.contentWindow.PDFViewerApplication.open(data);
};
</script>
I mean, when a user chooses the video file from their system, have the web-page already show them the files they want to upload.
I'm already using image file to preview using FileAPI JS. The same I want to do with FileAPI JS for video file.
(So, It must be work within my client side)
Thanks & answers are appreciated :)
You can either use FileReader or createObjectURL. They'll both get the job done, but FileReader has slightly broader support in browsers.
createObjectURL will run synchronously and return a Blob URL, a short string referencing the file in memory. and you can free it up immediately after you're done using it.
FileReader will run asynchronously, requiring a callback, providing a Data URI, a much longer string representing the whole file. This can be very big and will be freed from memory in Javascript garbage collection.
Here's an example that first tries createObjectURL and falls back to FileReader. (Please provide your own error checking, etc.)
var video = document.getElementById('video'),
input = document.getElementById('input');
input.addEventListener('change', function (evt) {
var reader = new window.FileReader(),
file = evt.target.files[0],
url;
reader = window.URL || window.webKitURL;
if (reader && reader.createObjectURL) {
url = reader.createObjectURL(file);
video.src = url;
reader.revokeObjectURL(url); //free up memory
return;
}
if (!window.FileReader) {
console.log('Sorry, not so much');
return;
}
reader = new window.FileReader();
reader.onload = function(evt) {
video.src = evt.target.result;
};
reader.readAsDataURL(file);
}, false);
Working example here: http://jsbin.com/isodes/1/edit
Mozilla has a more detailed article with instructions on how to upload once you've got your file.
IE10 supports both, but IE9 supports neither, so you'll have to fall back to a regular form upload without a preview.
Hy!
I need to upload a group of images using flex with robotlegs.
I need a progress bar to work when image is uploading.
It might upload 1 image or more at the time.
I want to know if uploading byteArray to server and then save the image is too heavy for the server.
In the server side I have a method that is made by pyamf, and looks like this:
.
def upload_image(input):
# here does stuff. I need to be able to get parametters like this
input.list_key
# and here I need some help on how to save the file
Thanks ;)
I had to tackle a similar problem (uploading single photo from Flex to Django) while working on captionmash.com, maybe it can help you. I was using PyAMF for normal messaging but FileReference class had a built in upload method, so I chose the easy way.
Basically system allows you to upload a single file from Flex to Google App Engine, then it uses App Engine's Image API to create thumbnail and also convert image to JPEG, then upload it to S3 bucket. boto library is used for Amazon S3 connection, you can view the whole code of the project here on github.
This code is for single file upload only, but you should be able to do multi-file uploads by creating an array of FileReference objects and calling upload method on all of them.
The code I'm posting here is a bit cleaned up, if you still have problems you should check the repo out.
Client Side (Flex):
private function upload(fileReference:FileReference,
album_id:int,
user_id:int):void{
try {
//500 kb image size
if(fileReference.size > ApplicationConstants.IMAGE_SIZE_LIMIT){
trace("File too big"+fileReference.size);
return;
}
fileReference.addEventListener(Event.COMPLETE,onComplete);
var data:URLVariables = new URLVariables();
var request:URLRequest = new URLRequest(ApplicationConstants.DJANGO_UPLOAD_URL);
request.method = URLRequestMethod.POST;
request.data = data;
fileReference.upload(request,"file");
//Popup indefinite progress bar
} catch (err:Error) {
trace("ERROR: zero-byte file");
}
}
//When upload complete
private function onComplete(evt:Event):void{
fileReference.removeEventListener(Event.COMPLETE,onComplete);
//Do other stuff (remove progress bar etc)
}
Server side (Django on App Engine):
Urls:
urlpatterns = patterns('',
...
(r'^upload/$', receive_file),
...
Views:
def receive_file(request):
uploadService = UploadService()
file = request.FILES['file']
uploadService.receive_single_file(file)
return HttpResponse()
UploadService class
import uuid
from google.appengine.api import images
from boto.s3.connection import S3Connection
from boto.s3.key import Key
import mimetypes
import settings
def receive_single_file(self,file):
uuid_name = str(uuid.uuid4())
content = file.read()
image_jpeg = self.create_jpeg(content)
self.store_in_s3(uuid_name, image_jpeg)
thumbnail = self.create_thumbnail(content)
self.store_in_s3('tn_'+uuid_name, thumbnail)
#Convert image to JPEG (also reduce size)
def create_jpeg(self,content):
img = images.Image(content)
img_jpeg = images.resize(content,img.width,img.height,images.JPEG)
return img_jpeg
#Create thumbnail image using file
def create_thumbnail(self,content):
image = images.resize(content,THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT,images.JPEG)
return image
def store_in_s3(self,filename,content):
conn = S3Connection(settings.ACCESS_KEY, settings.PASS_KEY)
b = conn.get_bucket(BUCKET_NAME)
mime = mimetypes.guess_type(filename)[0]
k = Key(b)
k.key = filename
k.set_metadata("Content-Type", mime)
k.set_contents_from_string(content)
k.set_acl("public-read")
This should be trivial, and I'm pretty sure I did it once before.
I'm trying to post data up to a server and have it bounced back to me as a file download, prompting the native browser file download box. I know the server part works just fine becasue I can post from a demo web form, but when I run the following Flex 3 code, I can't even get the request to fire.
var fileRef:FileReference = new FileReference();
private function saveXmlAsFile(event:MouseEvent):void
{
var fileRequest:URLRequest = new URLRequest();
fileRequest.method = URLRequestMethod.POST;
fileRequest.url = "http://foo.com/dataBounce";
var urlVariables:URLVariables = new URLVariables();
urlVariables.content = "Test content to return" ;
// fileRequest.contentType = "application/x-www-form-urlencoded ";
urlVariables.fileName = "test.xml";
fileRef.addEventListener(SecurityEvent.ALL, onSecurityError);
fileRef.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError2);
fileRef.addEventListener(IOErrorEvent.NETWORK_ERROR, onNetworkError);
fileRef.addEventListener(Event.COMPLETE, onComplete);
try
{
fileRef.download(fileRequest, "test.xml");
}catch(error:Error) {
model.logger.error("unable to download file");
}
}
Note, when the call to fileRef.download is called, I can't see any request being made across the network using the traditional Firebug or HTTPWatch browser tools.
EDIT: I should add that this is for < Flash Player 10, so I can't use the newer direct save as file functionality.
Any suggestions? Thanks.
You need to add fileRef.upload to trigger the upload.
Also I would move the download statement to the onComplete so the file isn't requested before it's been uploaded.
Your explanation is pretty clear, but when I look at your code, I'm feel like I'm missing something.
The code looks like you're trying to do half of the upload part and half of the download part.
I think the code you currently have posted would work to trigger a download if you set the .method value to GET. I believe you will also need to include the filename as part of the .url property.
However, to post something and then trigger a download of it, you need two separate operations - the operation to post the data and then an operation to download it, which should probably be called from the upload operation's onComplete handler.
OK, I believe I figured out one of the things that's going on.
When you don't set the URLRequest.data property, it defaults the request method to "GET".
So, the working code looks like, with the data set to the posted URL variables:
private var fileRef:FileReference;
private function saveRawHierarchy(event:MouseEvent):void
{
var fileRequest:URLRequest = new URLRequest();
fileRequest.method = URLRequestMethod.POST;
fileRequest.url = "http://foo/bounceback";
var urlVariables:URLVariables = new URLVariables();
urlVariables.content = "CONTENT HERE";
urlVariables.fileName = "newFileName.xml";
fileRequest.data = urlVariables;
fileRef = new FileReference();
fileRef.addEventListener(Event.COMPLETE, onComplete);
try
{
fileRef.download(fileRequest, "appHierarchies.xml");
}catch(error:Error) {
model.logger.error("unable to download file");
}
}
Not sure what was wrong about the request not being made before, though.