【问题标题】:HTTPHandler in VB.net for uploading files using PluploadVB.net 中的 HTTPHandler 用于使用 Plupload 上传文件
【发布时间】:2012-04-24 19:39:34
【问题描述】:

我已经构建了可以使用 Plupload 将多个图像上传到服务器的有效 VB.net 代码。我正在使用 HTTPHandler (FileUpload.ashx) 进行升级,并希望添加一条 SQL 语句,将每个图像文件名插入我的 SQL 数据库。我尝试将 SQL 添加到处理程序,但是当我这样做时,我会为每个上传的 iamge 获得 4 个数据库条目。我真的不明白为什么,需要一些指导。提前感谢您的时间。

相关的处理程序代码:

Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

    Dim chunk As Integer = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
    Dim fileName As String = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
    Dim fileUpload As HttpPostedFile = context.Request.Files(0)

    Dim uploadPath = context.Server.MapPath("Upload")
    Using fs = New FileStream(Path.Combine(uploadPath, fileName), If(chunk = 0, FileMode.Create, FileMode.Append))
        Dim buffer = New Byte(fileUpload.InputStream.Length - 1) {}
        fileUpload.InputStream.Read(buffer, 0, buffer.Length)

        fs.Write(buffer, 0, buffer.Length)
    End Using
    context.Response.ContentType = "text/plain"
    context.Response.Write("Success")

EXP:SQL 插入

        Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(DBCONN)
    Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand("W2_InsertPhoto " & fileName, conn)
    Dim rs As SqlClient.SqlDataReader
    conn.Open()
    rs = command.ExecuteReader()
    rs.Close()
    rs = Nothing
    conn.Close()
    conn = Nothing

【问题讨论】:

    标签: sql-server vb.net file-upload httphandler plupload


    【解决方案1】:

    如果你正在使用块,那么确保你触发你的 SQL,因为最后一个块已被保存

    例如。

      chunk = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
      chunks = If(context.Request("chunks") IsNot Nothing, Integer.Parse(context.Request("chunks")) - 1, 0) 
    
    
     If (chunk = chunks) Then
          'Upload is complete, Save to DB here or whatever
     end if
    

    -1 用在 CHUNKS 上,因为如果有意义的话,块是最后一个块的 -1。

    要获取文件名,您只需在 handler.ashx 中添加..

    fileName = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
    

    为了从 Pluplaod 获取唯一的文件名到你的处理程序,你需要告诉 Plupload(在客户端)使用唯一的名称。

    var uploader = new plupload.Uploader({
            runtimes: 'html5,flash,silverlight,html4',
            max_file_size: '20mb',
            url: '../handler.ashx',
            chunk_size: '100kb',
            unique_names: true,
            multipart_params: { imageType: $('#myDiv').attr("MyIMageType"), custom: 'This is static custom text' },
    

    在您的处理程序中,您再次调用 'name' 请求,您将拥有 pluplaoder 制作的 unqie 名称.. 还可以像往常一样请求多部分中的数据 request

    PictureType = If(context.Request("imageType") IsNot Nothing, [Enum].Parse(GetType(PictureType), context.Request("imageType")), Nothing)
    
    
    Dim myCustom as String = If(context.Request("custom") IsNot Nothing, context.Request("custom"))
    

    为了响应您的 SQL,您需要使用 ' 封装文件名,否则空格和特殊字符会破坏 SQLCommand,因为 SQL 会认为它是另一个变量或命令,而不是将其纯粹视为字符串。这也是SQL Injection的常见问题。因为这样的代码让黑客注入代码。

    【讨论】:

    • 感谢 ppumpkin 的回复。我可以使用您的代码并成功地为每个文件插入一条记录(而不是像以前那样插入多个记录)“这很好”......但我仍然无法使用“FileName”值为每个文件插入唯一的名称。我想我很困惑如果我在上传最后一个文件(如果块 -1)“之后”进行插入,我应该如何为我上传的每个文件获取唯一的文件名。
    • @Jason 我添加了更多示例。我还使用 jQuery $ 将一些数据放入 mulitpart。使用 fiddler 捕获发送过来的数据并调试您的处理程序,查看 context.current.request.forms 的参数。也请考虑支持或接受我的分析器。谢谢
    • 关于 sql 代码的观点,只是为了这篇文章,它做得又快又脏。我正在测试的图像没有任何特殊字符或空格。您对我遇到的问题有什么进一步的建议吗?很抱歉发布新问题,我不知道如何编辑我的问题并发布新的“代码”
    • 如果没有实际代码,我真的不能说。现在要调试了,提供实际代码确实有助于分配
    • ppumkin,你风度翩翩。我一直在外地从事其他项目。我刚回来,灯就亮了。我让它工作了,多亏了你。非常感谢!!!
    【解决方案2】:

    南瓜,我觉得我解释得不好。对不起,我确信这是蹩脚的条款,我是同时 plupload 和处理程序的新手。

    我使用唯一命名为“false”,因为我需要保留每个文件的原始名称。我目前在上传到服务器时正确命名了文件名,但是对于我的 SQL 插入,我需要插入这些相同的名称。如果我尝试使用我声明的 FileName (context.Request("name")) 作为我的 SQL 语句中的一个值,我会立即得到一个错误并且没有插入值。如果我为文件名使用静态值只是为了测试,它会很好地插入,但当然对于我上传的每个文件来说它的名称都是相同的。

    包括您的更新,这是我目前用于处理程序和客户端脚本的内容。

    处理程序:

    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
    
        Dim chunk As Integer = If(context.Request("chunk") IsNot Nothing, Integer.Parse(context.Request("chunk")), 0)
        Dim chunks As Integer = If(context.Request("chunks") IsNot Nothing, Integer.Parse(context.Request("chunks")) - 1, 0)
        Dim fileName As String = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
    
        If (chunk = chunks) Then
            Dim conn As SqlClient.SqlConnection = New SqlClient.SqlConnection(mdata.DBCONN)
            Dim command As SqlClient.SqlCommand = New SqlClient.SqlCommand("W2_InsertPhoto 12345," & **fileName**, conn)
            Dim rs As SqlClient.SqlDataReader
            conn.Open()
            rs = command.ExecuteReader()
            rs.Close()
            rs = Nothing
            conn.Close()
            conn = Nothing
        End If
    
        Dim fileUpload As HttpPostedFile = context.Request.Files(0)
    
        Dim uploadPath = context.Server.MapPath("Upload")
        Using fs = New FileStream(Path.Combine(uploadPath, fileName), If(chunk = 0, FileMode.Create, FileMode.Append))
            Dim buffer = New Byte(fileUpload.InputStream.Length - 1) {}
            fileUpload.InputStream.Read(buffer, 0, buffer.Length)
            fs.Write(buffer, 0, buffer.Length)
        End Using
    End Sub
    

    我的客户脚本:

        <script type="text/javascript">
        // Convert divs to queue widgets when the DOM is ready
        $(function () {
            $("#uploader").pluploadQueue({
                // General settings,silverlight,browserplus,html5gears,
                runtimes: 'flash',
                url: 'FileUpload.ashx',
                max_file_size: '10mb',
                chunk_size: '1mb',
                unique_names: false,
    
                // Specify what files to browse for
                filters: [{ title: "Image files", extensions: "jpg,jpeg,gif,png,bmp"}],
                // Flash settings
                flash_swf_url: 'assets/resources/plupload.flash.swf',
    
    
                // Silverlight settings
                silverlight_xap_url: 'assets/resources/plupload.silverlight.xap',
    
                init: {
                    FileUploaded: function (up, file, info) {
                    }
                }
            });
    
            // Client side form validation
            $('form').submit(function (e) {
                var uploader = $('#uploader').pluploadQueue();
    
                // Validate number of uploaded files
                if (uploader.total.uploaded == 0) {
                    // Files in queue upload them first
                    if (uploader.files.length > 0) {
                        // When all files are uploaded submit form
                        uploader.bind('UploadProgress', function () {
                            if (uploader.total.uploaded == uploader.files.length)
                                $('form').submit();
                        });
                        uploader.start();
                    } else
                        alert('You must at least upload one file.');
    
                    e.preventDefault();
                }
            });
            //tweak to reset the interface for new file upload
            $('#btnReset').click(function () {
                var uploader = $('#uploader').pluploadQueue();
    
                //clear files object
                uploader.files.length = 0;
    
                $('div.plupload_buttons').css('display', 'block');
                $('span.plupload_upload_status').html(''); 
                $('span.plupload_upload_status').css('display', 'none');
                $('a.plupload_start').addClass('plupload_disabled');
                //resetting the flash container css property
                $('.flash').css({
                    position: 'absolute', top: '292px',
                    background: 'none repeat scroll 0% 0% transparent',
                    width: '77px',
                    height: '22px',
                    left: '16px'
                });
                //clear the upload list
                $('#uploader_filelist li').each(function (idx, val) {
                    $(val).remove();
                });
            });
        });
    </script>
    

    【讨论】:

      猜你喜欢
      • 2013-04-29
      • 1970-01-01
      • 2013-12-14
      • 1970-01-01
      • 2011-07-21
      • 2011-07-22
      • 1970-01-01
      • 2023-04-08
      相关资源
      最近更新 更多