2012-04-12 3 views
2

Plupload를 사용하여 여러 이미지를 업로드하는 VB.net 코드를 작성했습니다. uplading을 수행하기 위해 HTTPHandler (FileUpload.ashx)를 사용하고 각각의 이미지 파일 이름을 SQL 데이터베이스에 삽입 할 SQL 문을 추가하려고합니다. 나는 핸들러에 SQL을 추가하려고 시도했지만, 업로드 할 때마다 각각의 iamge에 대해 4 개의 데이터베이스 항목을 얻는다. 나는 이유를 이해하지 못하고 어떤 지침이 필요하다. 미리 시간을내어 주셔서 감사합니다.Plupload를 사용하여 파일을 업로드하기위한 VB.net의 HTTPHandler

Pertainant 처리기 코드 :

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 

답변

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 말할 필요 클라이언트)가 고유 한 이름을 사용하도록합니다. 또한에서 평소와 같이 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")) 

를 수행 다중의 데이터를 요청 .. 핸들러에서

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 이름을 갖 귀하의 SQL에 대한 응답으로 파일 이름을 '으로 캡슐화해야합니다. 그렇지 않으면 공백과 특수 문자로 인해 SQLCommand가 중단됩니다. SQL은 순전히 문자열로 처리하는 대신 다른 변수 나 명령을 생각하기 때문입니다. 이것은 또한 SQL Injection의 공통적 인 문제이기도합니다. 이와 같은 코드로 인해 해커가 코드를 삽입 할 수 있도록 허용합니다.

+0

감사합니다. 나는 당신의 코드를 사용할 수 있으며, 성공적으로 "이렇게 좋음"과 같은 멀티플 인서트 대신에 파일 당 하나의 레코드를 삽입 할 수 있습니다. 그러나 여전히 "FileName"값을 사용하여 각 파일에 대해 고유 한 이름을 삽입 할 수 없습니다. 내가 마지막 파일 (청크 -1 인 경우)을 "삽입"한 후에 업로드하는 각 파일의 고유 한 파일 이름을 가져 오는 방법을 혼란스럽게 생각합니다. – Jason

+0

@ Jason 더 많은 예제를 추가했습니다. 또한 mulitpart에 데이터를 가져 오기 위해 jQuery'$ '를 사용합니다. 피들러를 사용하여 보내지는 데이터를 잡아 내고 처리기를 디버그하고, 매개 변수에 대해'context.current.request.forms'를 살펴보십시오. 또한 내 anser upvoting 또는 동의 고려하십시오. 감사합니다 – ppumkin

+0

포인트는 SQL 코드에 찍은,이 게시물에 대한 신속하고 더러운 일을했다. 테스트 할 iamges에는 특수 문자 나 공백이 없습니다. 내가 가지고있는 문제에 대한 제안이 있습니까? 새로운 질문을 게시하는 것에 대해 유감스럽게 생각합니다. 내 질문을 편집하고 실제 코드없이 새로운 "코드" – Jason

1

ppumpkin, 나는 자신을 잘 설명한다고 생각하지 않는다. 미안 나는 확실히 lamens 용어입니다, 나는 plupload 및 처리기를 동시에 모든 새로운 있습니다.

각 파일의 원래 이름을 유지해야하므로 고유 한 이름 지정을 "false"로 사용하고 있습니다. 현재 서버에 업로드 할 때 파일 이름의 이름을 올바르게 지정하고 있지만 SQL 삽입을 위해 동일한 이름을 삽입해야합니다. 만약 내가 (문명 ("name")) 문을 내 SQL 문에서 값으로 선언 한 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 

내 클라이언트 스크립트 : 회신 ppumpkin에 대한

<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> 
관련 문제