显示刚上传的图片

时间:2015-01-12 14:08:48

标签: jquery asp.net ajax

我让用户上传图片,效果很好。如果用户第一次加载页面,图像也会显示在Web表单上。

问题是当用户上传另一张图片(替换图片)时我希望新图片显示在页面上(使用ajax),但没有显示任何内容。

网络形式:

<asp:TextBox ID="txtVllID" runat="server" /><br />
<asp:Image ID="imgUploaded" runat="server" /><br />

服务器端脚本:

Public Sub Page_Load(ByVal sender As Object, ByVal args As EventArgs)

    If Page.IsPostBack Then
        Exit Sub
    End If

    'initieren
    txtVllID.Text = Nothing
    txtVllID.Text = Request.QueryString("vllid")
    imgUploaded.ImageUrl = "ImageHandler.ashx?vllid=" & txtVllID.Text

End Sub

ImageHandler.ashx

<%@ WebHandler Language="VB" Class="ImageHandler" %>

Imports System
Imports System.Web
Imports System.IO

Public Class ImageHandler : Implements IHttpHandler

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    Dim vllid = HttpContext.Current.Request.QueryString("vllid")
    context.Response.ContentType = "image/jpeg"
    context.Response.WriteFile("App_Themes/theme_yellow/uploads/" + vllid + ".jpg")
End Sub


Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
    Get
        Return False
    End Get
End Property

End Class

jQuery脚本:

<script type="text/javascript">
$(document).ready(function () {
    var settings = {
        url: "FileUploadHandler.ashx?vllid=" + $("#txtVllID").val(),
        allowedTypes: "jpg,jpeg,png,gif",
        onSuccess: function (files, response, xhr) {
            $.ajax({
                url: "ImageHandler.ashx?vllid=" + $("#txtVllID").val(),
                datatype: "image/jpg",
                success: function (data) {
                    //console.log(data); you see imagedata?(bytes?)
                    $("#imgUploaded").attr("src", data);
                }
            });
            $("#divGelukt").show("slow", function () { });
        }
    }
    $("#UploadArea").uploadFile(settings);
});
</script>

在屏幕上,图像不可见。当我在浏览器中查看结果代码时,imgUploades.src包含不可读的字符。如何将其显示为图像?

1 个答案:

答案 0 :(得分:0)

只需将img src设置为图片网址,而不是使用ajax下载。

    onSuccess: function (files, response, xhr) {
        $("#imgUploaded").attr("src", "ImageHandler.ashx?vllid=" + $("#txtVllID").val());
        $("#divGelukt").show("slow", function () { });
    }