使用ajax-webmethod上传asp.net图片

时间:2017-02-10 23:13:21

标签: asp.net ajax webmethod image-upload

HTML CODE

<script type="text/javascript">
    function sendFile(file) {
        var formData = new FormData();
        formData.append('file', $('#f_UploadImage')[0].files[0]);
        $.ajax({
            type: 'post',
            url: 'WebForm1.aspx/upload',
            data: formData,
            success: function (status) {
                if (status != 'error') {
                    var my_path = "MediaUploader/" + status;
                    $("#myUploadedImg").attr("src", my_path);
                }
            },
            processData: false,
            contentType: false,
            error: function () {
                alert("Whoops something went wrong!");
            }
        });
    }
    var _URL = window.URL || window.webkitURL;
    $("#f_UploadImage").on('change', function () {

        var file, img;
        if ((file = this.files[0])) {
            img = new Image();
            img.onload = function () {
                sendFile(file);
            };
            img.onerror = function () {
                alert("Not a valid file:" + file.type);
            };
            img.src = _URL.createObjectURL(file);
        }
    });
</script>

C#CODE

    [System.Web.Services.WebMethod]
    public static string upload(HttpContext file )
    {
        return "okey";
    }

如何捕获form-data中的值。如何在upload方法中使用变量类型表单数据。我尝试了一些变量(HttpContext,HttpPostedFile,object,Image)但不是我不想使用Generic Handler。请帮帮我。

1 个答案:

答案 0 :(得分:0)

假设您的FileUpload是这样的;

<input type="file" id="filebtn" runat="server" ... >

你可以抓住价值;

HttpPostedFile file = Request.Files["filebtn"];
string value = Path.GetFileName(file.FileName).ToString();