I need to upload and save an image onto the server. I am using an XMLHttpRequest POST to send the image to the server and calling a class named imageSave.aspx.
I am finding difficulty in "catching" the image from server side (imageSave.aspx) and saving it onto the server.
Does anyone please have some tips as to how this is done or maybe link to a good article or something?
Code used to perform the http POST....
xhr = new XMLHttpRequest();
// Update progress bar etc
xhr.upload.addEventListener("progress", function(evt) {
if (evt.lengthComputable) {
progressBar.style.width = (evt.loaded / evt.total) * 100 + "%";
}
else {
// No data to calculate on
}
}, false);
// File uploaded
xhr.addEventListener("load", function() {
progressBarContainer.className += " uploaded";
progressBar.innerHTML = "Uploaded!";
}, false);
xhr.open("post", "imageSave.aspx", true);
// Set appropriate headers
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", file.fileName);
xhr.setRequestHeader("X-File-Size", file.fileSize);
xhr.setRequestHeader("X-File-Type", file.type);
// Send the file
xhr.send(file);
Much appreciated,
JP
Read this other answer:
What data formats can AJAX transfer?
It'll get you an idea of why you can't upload an image using XMLHttpRequest.
UPDATE: Check this control of AJAX Control Toolkit - it'd be what you want! - :
http://www.asp.net/ajax/ajaxcontroltoolkit/samples/asyncfileupload/asyncfileupload.aspx
Related
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.
I am working on a Flash training video. I would like at the end of the video for a message to pop up with a dynamic confirmation code. I have the code for the confirmation code, but am having trouble creating something either at the end of the flash video or within the aspx page to trigger this message. Any thoughts or ideas of how to solve this would be greatly appreciated.
Thank You.
Depend on the purpose of the application, you can do either one. One thing to consider is does the user has to go through the flash video to obtain the code. If so, you need to organize the flow of the application in a way that the user can't cheat their way to obtain the code.
The ideal way is to have the flash called aspx page at the end of the movie to obtain the dynamic code. This can be done using URLLoader in ActionScript 3.0 or LoadVars in ActionScript 2.0.
URLLoader example
//this is the data
var data = "This is data";
//url of your aspx code
var request:URLRequest = new URLRequest("http://www.yourdomain.com/GenerateCode.aspx");
request.contentType = "text/xml";
request.data = data;
//use POST method
request.method = URLRequestMethod.POST;
var loader:URLLoader = new URLLoader();
try
{
//execute the request
loader.load(request);
}
catch (error:ArgumentError)
{
trace("There is an ArgumentError.");
}
LoadVars example:
//create LoadVars object
var lv_in:LoadVars = new LoadVars();
var lv_out:LoadVars = new LoadVars();
//set onLoad event
lv_in.onLoad = function(success:Boolean)
{
//if success, meaning data has received response from .net page, run this code
if (success)
{
//lv_in.status is use to get the posted data from .Net page
statusMsg.text = "Thank you!" + lv_in.status;
}
//if fail, run this code
else
{
statusMsg.text = "Error!";
}
}
//this is the data
lv_out.data = "This is data";
//begin invoke aspx page
lv_out.sendAndLoad("GenerateCode.aspx", lv_in, "POST");
There another easier way but not the best practice i should say. The easier way would be to direct user to aspx page that generate dynamic code after users finish the flash movie. The negative side is, the page can be accessed although users did not finish the flash movie.
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.
Generally the servlet extends httpservlet but in the code below
the servlet extends DataSourceServlet
and the page is created like this
The text begins with google.visualization.Query.setResponse
and ends with {c:[{v:'Bob'},{v:'Jane'}]}]}}); on the browser
code: http://code.google.com/apis/visualization/documentation/dev/dsl_csv.html
can you please guide me as to how can i make servlet page silent
without giving the output on the browser.? so that i can directly call the javascript page for drawing the chart
I want to integrate all the code but i am not able to remove this browser from coming.
I am new to servlet please help
Ok I will explain my doubt again
I am writting this servlet code
http://code.google.com/apis/visualization/documentation/dev/dsl_csv.html#intro
the url to execute is /CsvDataSourceServlet?url=http://localhost:8084/WebApplication1/F2.csv
When i execute this code i get output result on my browser ... I am not understanding how that code is opening my browser and showing
{c:[{v:'Bob'},{v:'Jane'}]}]}}); etc etc
why is this happening , why is the browser opening to show result
can we figure out something from this code
http://code.google.com/apis/visualization/documentation/dev/dsl_csv.html#intro
were F2.csv is my *.csv file
now after executing the code I have to display the result which i have to do using the javascript code as follows
All Examples
// Load the Visualization API and the ready-made Google table visualization.
google.load('visualization', '1', {'packages':['annotatedtimeline']});
// Set a callback to run when the API is loaded.
google.setOnLoadCallback(init);
// Send the queries to the data sources.
function init() {
//var query = new google.visualization.Query('simpleexample?tq=select name,population');
//query.send(handleSimpleDsResponse);
var query = new google.visualization.Query('CsvDataSourceServlet?url=http://localhost:8084/WebApplication1/F2.csv');
query.send(handleCsvDsResponse);
}
// Handle the csv data source query response
function handleCsvDsResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var chart = new google.visualization.AnnotatedTimeLine(document.getElementById('csv_div'));
chart.draw(data, {displayAnnotations: true});
}
CSV Data Source
An organization chart.
The data is taken from the csv data source.
I have an asp.net application that would 'simulate' real-time video. I did that acquiring multiple picture from an mysql database.
The problem is how would it be displayed on the web-page.? I refresh the page 1 second per picture, the result is the pictures are choppy and flickery.
Response.AppendHeader("Refresh", "1")
How can I make the refresh rate of the page 4times per second? or is there any implementation for it to be displayed in a continent way.
I would really appreciate if you will reply. good day (^_^)...
here is the script that i am using to read the images from the database,.
If dr.Read Then
dr.Read()
Response.ContentType = "image/jpeg" 'gets or sets the type of output stream
Response.BinaryWrite(dr.Item("file")) 'writes a stream of binary characters to the
http output stream
Else
Response.Write("There is no current active webccast.")
End If
dr.Close()
create a javascript method to change the image using xmlhttpobject and recursively set a timer
function Timer() {
setTimeout("getImage(['imageContainer1'])", 200);
t = setTimeout("Timer()", 100);
}
function getImage(params) {
var request=getXMLhttpObject();
makeRequest("ajax/ObtainImage.aspx?name='myimage'+param[1]+'.jpg",request, imageResponseHandler(request, params));
}
function getXMLhttpObject() {
return (navigator.appName == "Microsoft Internet Explorer")? new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();
}
function makeRequest(url,request, Handler) {
request.open("GET", url, true);
request.onreadystatechange = Handler;
request.send(null);
}
function imageResponseHandler(request,params) {
return function() {
if (request.readyState == 4)
document.getElementById(params[0]).src = request.responseText;
}
}
I would either use some Javascript/Ajax to change the content or the meta-refresh (probally not the best for fast refresh).
Maybe you need to think about loading more than one picture onto the page and using javascript to cycle between them. Rather than refreshing the page you could get the pictures using AJAX.
If you really want to simulate video, you need to be able to display at least 15 pictures each second (15fps). Making that many requests per second isn't a great idea.
If you absolutely must do this, I'd suggest "buffering" the pictures first, before displaying them, and if possible, fetching them in batches:
buffer = [] // cache loaded images
bufferSize = 30 // load 30 images before playing
function loadImage(src) {
var img = new Image()
img.src = src
buffer.push(img)
}
function animate(target) {
if (buffer.length > 0) {
var img = buffer.shift()
document.getElementById(target).src = img.src
}
}
function bufferImages() {
for (var i=0; i<bufferSize; i++) {
loadImage('/ajax/ObtainImage.aspx?name=img')
}
}
setInterval("animate('imgTarget')", 65) // should give us about 15fps
setInterval("bufferImages()", 1000) // every second
Add this to the head of your html document.
Not the most efficient way, but it will work.
<meta http-equiv="refresh" content=".25" />