我想使用ajax上传图片。 在这个模块中:
browse
并选择图片后,将上传并显示在文件栏位上。答案 0 :(得分:3)
您无法通过AJAX上传文件。您需要使用IFRAME或基于Flash的上传器。
答案 1 :(得分:2)
Actualy你可以在Jquery中使用ajax函数上传图像,至少是lates版本的chrome。
HTML:
<form action="/" enctype="multipart/form-data" method="post" accept-charset="utf-8">
<input type="file" name="image"/>
<button type="submit">
</form>
JS:
$("form").submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: window.location.pathname,
type: 'POST',
data: formData,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert(data);
}
});
return false;
});
此脚本将通过Ajax将包含创建的文件数据的发布请求发送到当前页面。您可以通过更改url参数来明显更改目的地。
答案 2 :(得分:1)
答案 3 :(得分:1)
假设你在服务器端有一个句柄..这里有一个小函数,以及如何在javascript中实现'iframe hack'的例子。
html
<form name="image-upload">
<input type="file" name="image" /></br>
<button type="submit" name="upload">Upload</button>
<div id="upload-results"></div>
</form>
javascript
var fileUpload = function(form /* HTMLElement */, action /* Form Action URL */, callback /* Callback function */) {
/* vars */
var atribs = {
"target": "upload_iframe",
"action": action,
"method": "post",
"enctype": "multipart/form-data",
"encoding": "multipart/form-data"
}, iframe;
/* iframe listener */
var ilistener = function() {
var results;
listener.remove(this, 'load', ilistener);
if( 'contentDocument' in this ) {
results = this.contentDocument.body.innerHTML;
} else if ( 'contentWindow' in this ) {
results = this.contentWindow.document.body.innerHTML;
} else if ( 'document' in this ) {
results = this.document.body.innerHTML;
} else {
throw "i'm dead jim :/";
}
callback.apply(this,[results]); // call the callback, passing the results
this.parentNode.removeChild(this); // remove the iframe
};
/* create the iframe */
form.parentNode.appendChild(FragBuilder([{"tagName": "iframe","id": "upload_iframe","name": "upload_iframe","style": {"height": "0","width": "0","border": "0"}}]));
/* collect the iframe back */
iframe = By.id('upload_iframe');
/* set the form properties */
for( var attr in atribs ) {
if( attr in form ) {
form[attr] = atribs[attr];
}
}
/* attach the event listener to the iframe */
listener.add(iframe, 'load', ilistener);
/* submitting the form */
form.submit();
};
// get the form, and the results area
var form = document.forms['image-upload'], results = By.id('upload-results');
// listen for the form submit, capture it, and run the iframe upload.
listener.add(form, 'submit', function(e) {
e.preventDefault();
results.innerHTML = 'Uploading...';
fileUpload(this, 'server.php' /* really anything */, function(data) {
console.log(data);
results.innerHTML = "Uploaded!";
});
});
请注意:为简单起见,我使用了以下实用程序。 来自JSON输入的https://github.com/rlemon/FragBuilder.js DocumentFragment构建器 https://gist.github.com/2172100事件监听器和By实用程序功能 *这些都很容易删除。