Sql server VB.net中的HTTPHandler,用于使用Plupload上载文件

Sql server VB.net中的HTTPHandler,用于使用Plupload上载文件,sql-server,vb.net,file-upload,httphandler,plupload,Sql Server,Vb.net,File Upload,Httphandler,Plupload,我已经构建了工作的VB.net代码,可以使用Plupload将多个图像上传到服务器。我正在使用HTTPHandler(FileUpload.ashx)进行上传,并希望添加一条SQL语句,将每个图像文件名插入到我的SQL数据库中。我已经尝试将SQL添加到处理程序中,但是当我添加SQL时,我会为每个上传的iamge获取4个数据库条目。我真的不明白为什么,需要一些指导。提前谢谢你的时间 相关处理程序代码: Public Sub ProcessRequest(ByVal context As HttpC

我已经构建了工作的VB.net代码,可以使用Plupload将多个图像上传到服务器。我正在使用HTTPHandler(FileUpload.ashx)进行上传,并希望添加一条SQL语句,将每个图像文件名插入到我的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 aster

比如说

  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用于区块,因为区块是最后一个区块的-1,如果这有意义的话

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

fileName = If(context.Request("name") IsNot Nothing, context.Request("name"), String.Empty)
为了将唯一的文件名从Plupload传递到处理程序,您需要告诉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注入的一个常见问题。。允许黑客因为这样的代码而注入代码。

ppumpkin,我认为我没有很好地解释自己。对不起,我确信是拉门术语,我对plupload和Handler都是新手

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

包括您的更新,这是我目前为我的处理程序和客户端脚本所做的

处理程序:

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>

//当DOM就绪时,将div转换为队列小部件
$(函数(){
$(“#上传器”).pluploadQueue({
//常规设置、silverlight、browserplus、html5gears、,
运行时:“flash”,
url:'FileUpload.ashx',
最大文件大小:“10mb”,
块大小:“1mb”,
唯一名称:false,
//指定要浏览的文件
过滤器:[{title:“图像文件”,扩展名:“jpg,jpeg,gif,png,bmp”},
//闪光设置
flash_swf_url:'assets/resources/plupload.flash.swf',
//Silverlight设置
silverlight_xap_url:'assets/resources/plupload.silverlight.xap',
初始化:{
上传文件:功能(上传、文件、信息){
}
}
});
//客户端表单验证
$('form')。提交(函数(e){
var uploader=$(“#uploader”).pluploadQueue();
//验证上载的文件数
if(uploader.total.uploader==0){
//队列中的文件首先上载它们
如果(uploader.files.length>0){
//上传所有文件后,提交表单
uploader.bind('UploadProgress',函数(){
if(uploader.total.upload==uploader.files.length)
$('form').submit();
});
uploader.start();
}否则
警报('您必须至少上载一个文件');
e、 预防默认值();
}
});
//调整以重置新文件上载的界面
$('#btnReset')。单击(函数(){
var uploader=$(“#uploader”).pluploadQueue();
//清除文件对象
uploader.files.length=0;
$('div.plupload_buttons').css('display','block');
$('span.plupload\u upload\u status').html(“”);
$('span.plupload_upload_status').css('display','none');
$('a.plupload_start').addClass('plupload_disabled');
//重置flash容器css属性
$('.flash').css({
位置:“绝对”,顶部:“292px”,
背景:“无重复滚动0%0%透明”,
宽度:“77px”,
高度:'22px',
左:“16px”
});
//清除上载列表
$('#uploader_filelist li')。每个(函数(idx,val){
$(val).remove();
});
});
});

谢谢您的回复。我可以使用您的代码,成功地为每个文件插入一条记录(而不是像以前那样多次插入),“这很好”。。。但我仍然无法使用“FileName”值为每个文件插入唯一的名称。如果我在上传最后一个文件(如果chunks-1)之后插入,我想我很困惑我该如何为我上传的每个文件获取唯一的文件名。@Jason我添加了更多的示例。我还使用jQuery
$
将一些数据获取到mulitpart中。使用fiddler捕获发送过来的数据并调试处理程序,查看
context.current.request.forms
中的参数。也请考虑接受或接受我的意见。ThanksPoint接受了sql代码,仅仅为了这篇文章,它做得又快又脏。我正在测试的iamges没有任何特殊字符或空格。你对我正在讨论的问题有什么进一步的建议吗?很抱歉发布新问题,我不知道如何编辑m