我正在解决尝试 upload an image via Ajax to Python 的问题。
第1步:只需让Ajax在页面上显示所选图像即可。
我在 Zurb 上发现了这篇有趣的文章,其中似乎有我需要的示例代码: http://zurb.com/playground/ajax-upload
$(document).ready(function() {
var thumb = $('img#thumb');
new AjaxUpload('imageUpload', {
action: $('form#newHotnessForm').attr('action'),
name: 'image',
onSubmit: function(file, extension) {
$('div.preview').addClass('loading');
},
onComplete: function(file, response) {
thumb.load(function(){
$('div.preview').removeClass('loading');
thumb.unbind();
});
thumb.attr('src', response);
}
});
我已经实现了插件并进行了设置,但是设置到 src 的响应是HTML页面本身,而不是图像。
当我在上传后检查缩略图的 src 路径时,我在 Zurb 的网站上发现了类似的问题。
也在我的 jsfiddle 中复制: http://jsfiddle.net/leongaban/cd5Hy/1/
你能看出我哪里出错了吗?
最佳答案
您可能没有采取正确的上传操作。
尝试创建将在服务器端处理图像的 PHP 文件,然后返回服务器上已有的图像数据:
<?php
$file = $_FILES['image']; // 'image' as you've set it in js code
$path = 'http://example.com/images/'; //path on the server where you gonna store your images. Remember to set proper directory permissions.
$location = $path. $_FILES["file"]["name"]; //this is where the file will go
move_uploaded_file($_FILES["file"]["tmp_name"], $location); // move the file there
echo $location; //send the file location back to the javascript
?>
现在,如果您想在将图像加载到服务器之前显示预览 - 尝试 HTML5 file upload handler
关于javascript - 如何修复 Ajax 图像上传 - 返回的响应是 HTML 而不是图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22183865/