Как загрузить изображение на сервер, используя JQuery ajax и без библиотеки, используя asp. net webform? - PullRequest
0 голосов
/ 20 марта 2020

Hellow,

Я нашел код, который позволяет перетаскивать изображение, отображаемое в зоне. и это успешно работает. Однако после многих испытаний я не смог загрузить файл. Я знаю, что путь будет поддельным, и его нельзя будет получить.

Я пытался использовать JQuery Ajax, чтобы вызвать метод «DataSave», который должен использовать инструмент загрузки файла для сохранения включенного образ. однако, он возвращает ноль !!

Какое решение было бы сохранить это изображение на сервере?

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

<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

<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#

    [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!";
    }

1 Ответ

0 голосов
/ 20 марта 2020

Попробуйте это:

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!");
    }
});

РЕДАКТИРОВАТЬ:

Вы можете добавить обобщенный c хандлер на стороне сервера (файл Ashx). Это будет выглядеть так (назовите 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;
    }
}

}

...