Reputation: 9436
Can you submit a form via AJAX that has a file type input? I am trying to use jquery to do this but it appears that it cannot serialize the file being submitted. Is this something that is blocked by the browser as a security concern? Is there a way around it?
Upvotes: 8
Views: 5775
Reputation: 41838
You can use the File API
, part of HTML5, to do this:
http://www.html5rocks.com/tutorials/file/dndfiles/
For a discussion on posting with it you can start with
http://groups.google.com/group/play-framework/browse_thread/thread/6223a9b25b87a839/6c74eda4f7b33010
Basically, using the File API
, javascript can read files from the local system, if the browser supports it, and then you can just post that through an ajax call, along with whatever else you need to submit.
If you need to submit multiple files, this may be a good starting point:
If you must use jQuery, then you can try this plugin, though I have never used it:
http://plugins.jquery.com/blueimp-file-upload-jquery-ui/
Upvotes: 3
Reputation: 40972
I downvoted Scott Harwell without giving a proper explanation of why I downvoted. I downvoted because this CAN be done and I do it consistently. My code is as follows:
html tag:
<form id="inputForm1" method="POST" enctype="multipart/form-data" ACTION="">
<div id="file-attachment">
<div style="float:left;">file:</div>
<div id="file-sub" style="float:left;">
<input type="file" id="WebAccessFile" name="WebAccessFile" size="45" value="">
</div>
</div>
</form>
the key is the enctype="multipart/form-data"
My jQuery ajax statement is as follows:
$.ajaxFileUpload({url:'/LonApps/FoxWeb.exe/EWI/ewiprocedures?Proc=addrelease',
secureuri: false,
fileElementId:'WebAccessFile',
dataType: 'text'
});
I use Visual FoxPro as my coding language for this function so I will post my VFP code but you can just adapt this code to which ever coding language you are using:
loAttachment = Request.FormFieldObject("WebAccessFile")
lcReleaseMessage = loAttachment.FileName
lcSaveFile = ""
IF loAttachment.ContentLength > 0
lcFileName = loAttachment.FileName
lcFileContent = loAttachment.Value()
lcSaveFile = "D:\Website\Publish\Depts\EWI\docs\" + lcFileName
SET SAFETY OFF
STRTOFILE(lcFileContent, lcSaveFile)
SET SAFETY ON
lcHTTPSaveFile = "/Publish/Depts/EWI/docs/" + lcFileName
ENDIF
This is receiving the input value as loAttachment (lo stands for Local Object). Then, among other things it is finding if the attachment content length is greater than 0, if it is then it is saving the attachment to a local web directory for later access.
Upvotes: 2
Reputation: 7465
The technical answer is no, but there are "hacks" to post your form to a hidden iFrame in order to appear as if it is Ajax. A google search should yield many examples.
Upvotes: 0