简体   繁体   English

如何使用JQuery ajax而不使用asp.net webform将图像上传到服务器端?

[英]how to upload image to server side using JQuery ajax and without library using asp.net webform?

Hellow,你好,

I found a code that allows me to drag and drop an image to be displayed in a zone.我找到了一个代码,它允许我拖放要在区域中显示的图像。 and it works successfully.它工作成功。 However, after many trials, I couldn't be able to upload the file.但是,经过多次试验,我无法上传文件。 I know the path is will be fake and it is not allowed to be retrieved.我知道路径是假的,不允许检索。

I have tried to use JQuery Ajax to trigger a method "DataSave" that should use fileupload tool to save the included image.我尝试使用 JQuery Ajax 来触发一个方法“DataSave”,该方法应该使用文件上传工具来保存包含的图像。 however, it returns null !!但是,它返回 null !

what would be the solution to save this image at the server?将此图像保存在服务器上的解决方案是什么?

HTML HTML

    <div id="dropzone">
        <div>dropzone</div>
        <asp:FileUpload ID="FileUploadControl" runat="server" />
    </div>
    <asp:Label ID="StatusLabel" runat="server" Text="Label"></asp:Label>

CSS CSS

<style>
    #dropzone {
        position: relative;
        border: 5px dotted #000;
        border-radius: 10px;
        color: #000;
        font: bold 24px/200px arial;
        height: 200px;
        margin: 30px auto;
        text-align: center;
        width: 200px;
    }

        #dropzone.hover {
            border: 4px solid green;
            color: green;
        }

        #dropzone.dropped {
            background: #222;
            border: 5px solid #444;
        }

        #dropzone div {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }

        #dropzone img {
            border-radius: 5px;
            vertical-align: middle;
            max-width: 95%;
            max-height: 95%;
        }

        #dropzone [type="file"] {
            cursor: pointer;
            position: absolute;
            opacity: 0;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
        }
</style>

JavaScript JavaScript

<script>
    $(function () {

        var dropzone = $("#dropzone"),
            input = dropzone.find('input');

        dropzone.on({
            dragenter: dragin,
            dragleave: dragout
        });

        input.on('change', drop);

        function dragin(e) { //function for drag into element, just turns the bix X white
            $(dropzone).addClass('hover');
        }

        function dragout(e) { //function for dragging out of element                         
            $(dropzone).removeClass('hover');
        }

        function drop(e) {
            var file = this.files[0];

            $('#dropzone').removeClass('hover').addClass('dropped').find('img').remove();

            // upload file here
            showfile(file); // showing file for demonstration ... 
        }

        function showfile(file) {

            //var fd = new FormData();
            //var files = file;
            //fd.append('file', files);

            var reader = new FileReader(file);
            reader.readAsDataURL(file);
            reader.onload = function (e) {
                $('#dropzone div').html($("<img id='img' />").attr('src', e.target.result).fadeIn());
            };

            $.ajax({
                type: "POST",
                url: "dragapleImage.aspx/DataSave",
                    <%-- data: '{MyImg: "' + $("#<%=FileUploadControl.ClientID%>")[0].value + '" }',--%>
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: OnSuccess,
                    failure: function (response) {
                        alert(response.d);
                    }
            });
            function OnSuccess(response) {
                alert(response.d);
            }
        };

    });

 </script>

C# C#

    [WebMethod]
    public static string DataSave(string MyImg)
    {
        HttpPostedFile fileup = HttpContext.Current.Request.Files["FileUploadControl"];
        string filename = Path.GetFileName(fileup.FileName);
        fileup.SaveAs("~/" + filename);      
        return "Upload status: File uploaded!";
    }

Try this:尝试这个:

var formData = new FormData();
formData.append('file', $('#FileUploadControl')[0].files[0]);

$.ajax({
    type: 'post',
    url: 'saveImage.ashx',
    data: formData,
    success: function (status) {
        if (status != 'error') {
            alert("ok!");
        }
    },
    processData: false,
    contentType: false,
    error: function () {
        alert("Sorry!");
    }
});

EDIT:编辑:

You can add a generic hundler in the server side (ashx file).您可以在服务器端(ashx 文件)中添加一个通用的 hundler。 It will look like this (name it saveImage.ashx and don't forget to change &.ajax url!):它看起来像这样(将其命名为 saveImage.ashx 并且不要忘记更改 &.ajax url!):

using System;
using System.Web;
using System.IO;
public class fileUploader : IHttpHandler {

public void ProcessRequest(HttpContext context)
{
    context.Response.ContentType = "text/plain";
    try
    {
        string dirFullPath = HttpContext.Current.Server.MapPath("~/MediaUploader/");
        string[] files;
        int numFiles;
        files = System.IO.Directory.GetFiles(dirFullPath);
        numFiles = files.Length;
        numFiles = numFiles + 1;
        string str_image = "";

        foreach (string s in context.Request.Files)
        {
            HttpPostedFile file = context.Request.Files[s];
            string fileName = file.FileName;
            string fileExtension = file.ContentType;

            if (!string.IsNullOrEmpty(fileName))
            {
                fileExtension = Path.GetExtension(fileName);
                str_image = "MyPHOTO_" + numFiles.ToString() + fileExtension;
                string pathToSave_100 = HttpContext.Current.Server.MapPath("~/MediaUploader/") + str_image;
                file.SaveAs(pathToSave_100);
            }
        }
        //  database record update logic here  ()

        context.Response.Write(str_image);
    }
    catch (Exception ac) 
    { 

    }
}

public bool IsReusable {
    get {
        return false;
    }
}

} }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 我如何在asp.net的服务器端上传图像 - how can I upload a image on server side in asp.net 如何使用ASP.NET MVC4在单击时使用jquery在不使用任何形式的情况下上载文本框中的图像和文本 - How to upload image and the text in a textbox without using any form using jquery on click using ASP.NET MVC4 在asp.net中使用ajax调用服务器端方法 - call server side method using ajax in asp.net 使用ajax上传的文件返回错误,但使用c#在asp.net的服务器端正常提交的文件 - Files upload using ajax returns error but files submitted normally on server side in asp.net using c# 使用 asp.net 从数据库中获取图像并显示在网络表单中 - getting image from database and display in the webform using asp.net 如何使用jquery ajax在asp.net mvc中使用文件上传附加多个文件 - how attach multiple file in using file upload in asp.net mvc using jquery ajax 如何在不使用文件上传的情况下在asp.net JQuery中获取文件名并上传文件 - How to get FileName and upload file in asp.net JQuery without using File Upload 如何在不使用ASP.NET服务器端控件的情况下从C#ASP.NET中读取HTML文件类型的输入流 - How to read inputstream from HTML file type in C# ASP.NET without using ASP.NET server side control 如何在asp.net中使用ajax调用上传文件? - How to Upload Files using ajax call in asp.net? 如何在不使用静态方法的情况下在asp.net中调用服务器端方法 - how to Call server side method in asp.net without using static method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM