javascript - 如何修复 Ajax 图像上传 - 返回的响应是 HTML 而不是图像

标签 javascript jquery ajax file-upload

我正在解决尝试 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页面本身,而不是图像

enter image description here

当我在上传后检查缩略图的 src 路径时,我在 Zurb 的网站上发现了类似的问题。

enter image description here

也在我的 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/

相关文章:

javascript - 更改 y 轴上刻度的大小并在 D3.js 中添加图例

javascript - 如何在 &lt;script setup> Vue3 中使用渲染功能

javascript - 为 D3 和 SVG 元素创建动画

javascript - 多个复选框元素的 querySelectorAll 的 onchange 监听器

javascript - 如何从异步调用返回响应?

javascript - 无法以正确的顺序将 JQuery 链接到 HTML

javascript - 获取对象中具有最大索引键的属性

javascript - 如何动态设置iframe高度?

json - 如何在ajax调用中压缩web服务响应json

javascript - 如何从异步调用返回响应?