2015-05-25 97 views
0

我正在使用從blueimp上的jquery-file-upload(https://blueimp.github.io/jQuery-File-Upload/)。使用ashx filehandler和ajax上傳文件總是返回錯誤

我有FileHandler.ashx文件上傳。

我無法從文件處理程序返回正確的響應。在JavaScript方面,它總是收到錯誤。請引導我。

//文件句柄(FileHandler.ashx)

public void ProcessRequest(HttpContext context) 
    { 
     string fname = String.Empty; 
     if (context.Request.Files.Count > 0) 
     { 
      HttpFileCollection files = context.Request.Files; 
      for (int i = 0; i < files.Count; i++) 
      { 
       HttpPostedFile file = files[i];      
       fname = context.Server.MapPath("~/UserImageUploads/" + file.FileName); 
       file.SaveAs(fname); 
      } 
     } 
     context.Response.ContentType = "text/plain"; 
     context.Response.Write(fname); 
     context.Response.StatusCode = 200; 
    } 

// JavaScript部分:

$(function() { 
    'use strict'; 
    // Change this to the location of your server-side upload handler: 
    var url = 'FileHandler.ashx'; 
    $('#fileupload').fileupload({ 
     url: url, 
     dataType: 'json', 
     done: function (e, data) { 

     }, 
     fail: function (e, data) { 

     }, 
    }); 
}); 

的resut始終 「失敗」,也不會 「成功」。錯誤是SyntaxError: Unexpected token C。 這與我回復的迴應有些相關,它的格式不正確,但它應該在那裏格式?

回答

1

嘗試這樣的事情

public class ResponseMsg 
    { 
     public string status; 
     public string name; 
    } 

public void ProcessRequest(HttpContext context) 
    { 
     string fname = String.Empty; 
     if (context.Request.Files.Count > 0) 
     { 
      HttpFileCollection files = context.Request.Files; 
      for (int i = 0; i < files.Count; i++) 
      { 
       HttpPostedFile file = files[i];      
       fname = context.Server.MapPath("~/UserImageUploads/" + file.FileName); 
       file.SaveAs(fname); 
      } 
     } 
     context.Response.ContentType = "text/plain"; 
     // context.Response.Write(fname); 
     // context.Response.StatusCode = 200; 

     ResponseMsg r = new ResponseMsg 
     { 
      status = "success", 
      name =fname 
     }; 
     context.Response.Write(JsonConvert.SerializeObject(r)); 
    }