2012-07-17 2 views
3

아약스를 통해 텍스트 콘텐츠를 업로드하려고하는데, 나중에 구문 분석됩니다. Ajax 업로드 및 ASP.NET

$("#fuFile").change(function() { 
      var fileInput = document.getElementById("fuFile"); 
      var file = fileInput.files[0]; 
      var formdata = new FormData(); 
      formdata.append('file', file); 

      var xhr = new XMLHttpRequest(); 
      xhr.open("POST", 'testhandler.ashx', true); 
      xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); 
      xhr.setRequestHeader("X-File-Name", file.name); 
      xhr.setRequestHeader("Content-Type", "application/octet-stream"); 
      xhr.send(formdata);    

}); 

fuFile 내 파일 입력하고, testhandler.ashx는 업로드 된 파일을 가져옵니다 서버 핸들러 : 그건 내 자바 스크립트 코드입니다. 나는이 작업을 수행 할 때

을 (. 실제로 파일 내용을 분석하기 위해 다른 핸들러를 사용)하지만 :

HttpFileCollection fc = context.Request.Files; 

그것은 어떤 파일을 반환하지 않습니다. 그러나 IE에서 작동합니다.

하지만 입력 스트림 얻을하려고하면

StreamReader stream = new StreamReader(context.Request.InputStream); 
    string text = stream.ReadToEnd(); 

하게되었을 때 text 변수 (HTTP 헤더) + 파일 내용을. OK,하지만이 플러그인을 사용했습니다

------WebKitFormBoundaryx16Mw7tnG6JeflIB\r\nContent-Disposition: form-data;name=\"file\"; filename=\"teste export.CSV\"\r\nContent-Type: application/vnd.ms-excel(..file content..) 

: 나는의 InputStream을 통해 내용을 얻을 수 http://valums.com/ajax-upload/

을 그리고 플러그인 마녀 만 파일 내용 나를 돌아, 나는 어떤을받지 않은 HTTP 머리글.

그건 완벽하지만 플러그인을 사용하지 않고 업로드 스크립트를 만들고 싶습니다. 업로드하고 분석하여 결과를 반환하십시오. 간단하고 빠른

내 질문은 : Ajax XHR에서 업로드 한 파일 내용을 가져 오는 방법, 모든 브라우저에서 파일 내용 만 가져 오는 방법?

+0

http://stackoverflow.com/questions/ 10475313/ajax-file-upload-with-xmlhttprequest도 비슷한 질문입니다. 여기 xhr2의 브라우저 지원에 대한 정보가 있습니다. http://caniuse.com/xhr2 –

+0

예, 내 브라우저는 xhr2를 지원합니다. 그리고 비슷한 질문이 내 문제와 비슷하지 않았습니다 ... –

+1

이것을 읽으셨습니까 http://stackoverflow.com/questions/7595049/why-cant-i-upload-files-asynchronously? – Vismari

답변

0

그것은 나를 위해 일이고 내가 당신을 도울 수 있다고 생각

내 JS 기능 :

$("#fuFile").click(function() { 
    var fileInput = document.getElementById("fuFile"); 
    var file = fileInput.files[0]; 
    var fd = new FormData(); 
    fd.append("files", file); 
    var xhr = new XMLHttpRequest(); 

    xhr.open("POST", 'http://localhost:63186/UploadFile.ashx'); 

    xhr.send(fd); 

}); 

내 처리기 :

string filePath = "~/Files/"; 

     //write your handler implementation here. 
     if (context.Request.Files.Count <= 0) 
     { 
      context.Response.Write("No file uploaded"); 
     } 
     else 
     { 
      for (int i = 0; i < context.Request.Files.Count; ++i) 
      { 
       HttpPostedFile file = context.Request.Files[i]; 
       var fileInfo = new FileInfo(file.FileName); 
       file.SaveAs(context.Server.MapPath(filePath + fileInfo.Name)); 
       context.Response.Write("File uploaded"); 
      } 
     }