|
-
Mar 15th, 2015, 03:04 PM
#1
Thread Starter
Member
File upload through Ajax
Folks,
I'm going through tutorials about uploading file through Ajax. This one, this one, and another one. They are very similar. Both stuff the data into an object and post it with $.ajax(...) . So far so good.
There is a line
Code:
m_data.append( 'file_attach', $('input[name=file_attach]')[0].files[0]);
What is the first [0] for? Why is it required? Where can I read more about the files[] array?
Any suggestion, insight or reference is really appreciated!
Best,
-Nick
-
Mar 15th, 2015, 05:44 PM
#2
Re: File upload through Ajax
Some useful links for reading:
https://developer.mozilla.org/en-US/...b_applications
https://developer.mozilla.org/en-US/docs/Web/API/File
https://developer.mozilla.org/en-US/...b/API/FileList
In short, you are selecting the file input on name attribute, not id. Multiple elements on a page can share the same name attribute, so you have [0] to select the first one in the list returned by the jQuery selector.
Each file input element can select multiple files for upload with the multiple attribute, hence having a files property instead of just singular file.
-
May 27th, 2015, 09:48 AM
#3
New Member
Re: File upload through Ajax
-
May 27th, 2015, 12:50 PM
#4
Re: File upload through Ajax
Here's how I do ajax-like uploads in an inner FORM/IFRAME
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<link href="../css/AWCOffice.css"rel="stylesheet" type="text/css" />
<link href="../css/Final.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" onsubmit="return false;" runat="server">
<div id="acs-edit-bidsbid" style="padding-left: 10px; padding-top: 10px;">
.
.
. Step #1 - Browse for file to upload and click Upload button
<span class="acs-span-large">Upload Key</span>
<label class="awc-UpId awc-ctrlval1 acs-edit-small-text"></label>
<br />
<br />
<form action="Upload.ashx" method="post" enctype="multipart/form-data" target="upload_target_view1">
<div>
<label>
<input type="file" name="file" multiple>
</label>
<br /><br />
<button type="submit" name="username" value="(awc_UploadCreate_Bid)" class="ui-button ui-widget ui-state-highlight ui-corner-all ui-button-text-icon-acs-use ui-button-text-icon-primary" role="button" aria-disabled="false">Upload</button>
</div>
<iframe name="upload_target_view1" class="acs-dlg-upload">
<html>
<head></head>
<body></body>
</html>
</iframe>
</form>
<ul id="filelist">
</ul>
<br />
Then using jQuery I "find" that DIV with the CSS "acs-dlg-upload"
Code:
wesUP = wesEP.find(".acs-dlg-upload");
if (wesUP.length != 0) {
wesUPS = wesUP.siblings().find("button:submit");
strUPS = wesUPS.attr("value") || "";
strUPS = (window.username || "") + strUPS;
wesUPS.attr("value", strUPS)
wesUP.load(function () {
var strResult = wesUP.contents().find("body").html();
if (strResult.length != 0) {
uploadComplete(strEditPanel, strResult);
}
return false;
});
}
That wires up the uploadComplete function for the LOAD event of the IFRAME
Code:
function uploadComplete(strId, strResult) {
var returnObj = $.parseJSON(strResult);
var updArr = returnObj.update || [];
var strData = "";
var wesAWC = [];
for (var i = 0; i < updArr.length; i = i + 2) {
strData = updArr[i + 1];
wesAWC = $(strId + " .awc-" + updArr[i]).not(".acs-edit-view-hidden");
p_fillField(wesAWC, strData, strId, updArr[i], false);
}
if (returnObj.ok) {
errorMessage("Upload Complete", returnObj.message);
} else {
errorMessage("Upload DID NOT Complete", returnObj.message);
}
return false;
}
And the FORM talks to an upload page - indicated in this line of the HTML
<form action="Upload.ashx" method="post" enctype="multipart/form-data" target="upload_target_view1">
And that page - in VB.Net - looks like this
Code:
<%@ WebHandler Language="VB" Class="Upload" %>
Imports System
Imports System.Web
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Public Class Upload : Implements IHttpHandler
Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim username As String = context.Request.Params("username")
Dim credDB As String = ""
Dim overSproc As String = ""
If username.EndsWith(")") Then
Dim cp As Integer = username.LastIndexOf("(")
overSproc = username.Substring(cp + 1, username.Length - cp - 2)
username = username.Substring(0, cp)
End If
If username.Contains(":") Then
credDB = username.Split(":"c)(0)
username = username.Split(":"c)(1)
End If
Dim postedFile As HttpPostedFile = context.Request.Files("file")
which finishes up like this
Code:
postedFile.SaveAs(Path.Combine(savepath, StoredFileName))
strResp &= "{ ""ok"": true"
strResp &= ", ""message"": """ & Message & """"
strResp &= ", ""update"": " & Update
strResp &= "}"
context.Response.Write(strResp) 'filename)
context.Response.StatusCode = 200
End If
End If
Catch ex As Exception
strResp = "{""ok"": false, ""message"": ""Error: " & ex.Message.Replace("""", "'").Replace("\", "\\") & ".""}"
context.Response.Write(strResp) 'filename)
context.Response.StatusCode = 200
End Try
End Sub
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
-
Jul 31st, 2015, 05:58 AM
#5
Banned
Re: File upload through Ajax
File upload through Ajax
//form html
<p id="status"></p>
<form id="form1" enctype="multipart/formdata">
<input type="file" id="photo" name="photo" />
<input type="submit" id="save" name="save" value="Upload" />
</form>
//php file
if($_POST){
$name = $_POST['photo']['name'];
$tmp = $_POST['photo']['tmp_name'];
$path = "images/".basename(name);
if(move_uploaded_file($tmp,$path)){
print("Done! File saved...");
}else{
die("Error on uploading!")
}
}
//js
$(document).ready(function(){
var photo = $("#photo").val();
$.post("upload.php",{photo  hoto},function(data){
$("#status").html(data);
});
});
-
Jul 31st, 2015, 07:05 AM
#6
Re: File upload through Ajax
@beingchinmay - I'm curious - does that refresh the page that requested the upload?
-
Jul 31st, 2015, 08:27 AM
#7
Banned
Re: File upload through Ajax
-
Jul 31st, 2015, 10:00 AM
#8
Re: File upload through Ajax
Yes - I see that now that I look closely.
Your example is the main form in the page though - right? My example is in an iframe.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|