使用 Ajax 和 ASP.NET 将图像上传并保存到服务器,无需刷新

问题描述 投票:0回答:2

我有一个 VB ASP.net 页面,允许用户上传、裁剪和保存图像,这发生在对话框中,所以我不想刷新页面。所以,我正在尝试使用 Ajax,但不确定是否可行。

有没有办法让这个工作使用我的代码?如果没有,有一个简单的解决方案吗?

注意:我测试了所有这些 ASP 代码并且在没有 Ajax 的情况下工作得很好

常规上传是这样的:

Private Sub btnUpoadToCrop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpoadToCrop.Click

    Dim objUpload As New Upload
    objUpload.MaxLength = 4000000

    '''' Upload Image File
    If objUpload.FileFieldLength(flImg) <> 0 Then

        Dim flImg As HttpPostedFile = Request.Files(0)
        Dim oFolder As String = "\media\temp-uploads\"
        Dim strName As String = System.IO.Path.GetFileName(flImg.FileName).Replace(" " & "%20", "_").ToString
        Dim oFile As String = oFolder + strName

        '''' Save Original Photo
        flImg.SaveAs(HttpContext.Current.Server.MapPath(oFile))


    End If

End Sub

尝试 AJAX

因为我无法访问 flImg 图像文件,所以尝试从 Ajax 发送变量,这对我不起作用,并且控制台返回 500(内部服务器错误)

VB.NET

   Public Shared Function UploadSource(ByVal src As String, ByVal strName As String, ByVal ext As String) As String

    '''' Upload Image File

    Dim filesCollection As HttpFileCollection = HttpContext.Current.Request.Files
    Dim fileName = filesCollection(0)
    Dim Name As String = System.IO.Path.GetFileName(fileName.FileName).Replace(" " & "%20", "_").ToString

    Dim oFolder As String = "\media\temp-uploads\"
    Dim oFile As String = oFolder + Name

    '''' Save Original Photo

    fileName.SaveAs(HttpContext.Current.Server.MapPath(oFile))

End Function

j查询

    $(document).ready(function() {

        // Ajax Upload
        var _src, _path, _name, _ext;
        $("#<%= flImg.ClientID%>").change(function () {
            //console.dir(this.files[0]);
            var val = $(this).val();    
            if (val != "") {
                _src = val;
                _name = _src.substr(0, _src.lastIndexOf('.'));
                _ext = _src.split('.').pop();
                _ext = _ext.toLowerCase();
                alert(_ext);
            }
            else {
                _src = "";
            }
        }).trigger('change');
        $(document).on("click", "#UploadSource", function () {
            if (_src != "") {
                alert(_name);
                $.ajax({
                    type: 'POST',
                    contentType: "application/json; charset=utf-8",
                    url: '/ImgCropper.aspx/UploadSource',
                    // *** I have set values for variables for test
                    data: "{'src':'" + "xyz.jpg" + "','name':'" + "xyz"+ "','ext':'" + "jpg" + "'}",
                    async: false,
                    success: function (response) {

                   },
                   error: function () {
                       alert("some problem in saving data");
                   }
               });
            }


        });
     });

然后尝试使用此函数在 Ajax 数据中不发送变量,但仍然没有希望:

Public Shared Function UploadSource() As String


    '''' Upload Image File

    Dim filesCollection As HttpFileCollection = HttpContext.Current.Request.Files
    Dim fileName = filesCollection(0)
    Dim Name As String = System.IO.Path.GetFileName(fileName.FileName).Replace(" " & "%20", "_").ToString


    Dim oFolder As String = "\media\temp-uploads\"
    Dim oFile As String = oFolder + Name

    '''' Save Original Photo
    fileName.SaveAs(HttpContext.Current.Server.MapPath(oFile))


End Function
jquery asp.net ajax vb.net file-upload
2个回答
0
投票

请使用下面的链接下载ajax文件uplod脚本。

http://www.phpletter.com/DOWNLOAD/

那么你的代码应该如下所示。

HTML:

<input type="file" id="fileupload" name="upload"/>

<asp:LinkButton ID="btnSave" runat="server" Text="Save" Width="52px"  OnClientClick="UploadFile();" />

Jquery:

$(document).ready(function () {
function UploadFile() {
var fileName = $('#fileupload').val().replace(/.*(\/|\\)/, '');

if (fileName != "") {
                $.ajaxFileUpload({ url: 'AjaxFileUploader.ashx',
                    secureuri: false,
                    fileElementId: 'fileupload',
                    dataType: 'json',
                    success: function (data, status) {
                        if (typeof (data.error) != 'undefined') {
                            if (data.error != '') {
                                alert(data.error);
                            } else {
                                alert('Success')
                            }
                        }
                    },
                    error: function (data, status, e) {
                        alert(e);
                    }
                }
                )
            }
}

});

AjaxFileUploader.ashx:

<%@ WebHandler Language="VB" Class="AjaxFileUploader" %>
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.IO
Imports System.Text.RegularExpressions
Imports System.Text
Public Class AjaxFileUploader
    Implements IHttpHandler
    Implements System.Web.SessionState.IRequiresSessionState

    Public Sub ProcessRequest(context As HttpContext)


        If context.Request.Files.Count > 0 Then
            Dim path__1 As String = context.Server.MapPath("~/Uploads")
            If Not Directory.Exists(path__1) Then
                Directory.CreateDirectory(path__1)
            End If

            Dim file = context.Request.Files(0)

            Dim fileName As String

            If HttpContext.Current.Request.Browser.Browser.ToUpper() = "IE" Then
                Dim files As String() = file.FileName.Split(New Char() {"\"C})
                fileName = files(files.Length - 1)
            Else
                fileName = file.FileName
            End If
            Dim newFile As String = Guid.NewGuid().ToString()
            Dim fInfo As New FileInfo(fileName)
            newFile = String.Format("{0}{1}", newFile, fInfo.Extension)
            Dim strFileName As String = newFilename
            fileName = Path.Combine(path__1, newFile)
            file.SaveAs(fileName)


            Dim msg As String = "{"
            msg += String.Format("error:'{0}'," & vbLf, String.Empty)
            msg += String.Format("msg:'{0}'" & vbLf, strFileName)
            msg += "}"


            context.Response.Write(msg)
        End If
    End Sub

    Public ReadOnly Property IsReusable() As Boolean
        Get
            Return True
        End Get
    End Property
End Class

0
投票

您可以如下编写WebMethod(C#语言)

[WebMethod]
public string UploadFile()
        {
                var httpPostedFile = HttpContext.Current.Request.Files["UploadedImage"];
                //Your logic to save httpPostedFile
            }
        }

在页面上您可以使用 jQuery 发送文件,如下所示,

<html>
<div>
        Select File to Upload:
        <input id="fileUpload" type="file" />
        <input id="btnUploadFile" type="button" value="Upload File" /></div>
 <script type="text/javascript">

    $('#btnUploadFile').on('click', function () {
    $('#<%=hdnFileName.ClientID %>').val('');
        if (typeof FormData == "undefined") {
            alert("Please Use Latest Version Of Google Chrome Or Mozilla Firefox To Upload Documents");
            return false;
        }
                    var data = new FormData();

                    var files = $("#fileUpload").get(0).files;

                    // Add the uploaded image content to the form data collection
                    if (files.length > 0) {
                        data.append("UploadedImage", files[0]);
                    }
    else{
    alert('Please Select File');
    return;
    }

                    var ajaxRequest = $.ajax({
                        type: "POST",
                        url: "http://localhost/WebSite/WebPage.aspx/UploadFiles",
                        contentType: false,
                        processData: false,
                        data: data
                    });

                    ajaxRequest.done(function (data) {
                        console.log(data);
                        alert("done");
                    });

                    ajaxRequest.error(function (xhr, status) {
                        console.log(xhr);
                        console.log(status);
                        alert(status);
                    });
                });
</script>
</html>

记住,它可能无法在某些版本的 IE 上运行,否则在 Chrome 和 Firefox 中可以顺利运行。

© www.soinside.com 2019 - 2024. All rights reserved.