我有一个C#方法,如果你从另一个C#方法调用它,但不是从JavaScript调用。我如何使我的ajax调用工作?如何从System.Web.HttpContext.Current.Response.BinaryWrite(byteArray)中下载文件;从JavaScript而不是C#
我需要基于传入的ID来获取文件,所以我有一个带有statusID的ajax文章。该ID正在我的C#方法中拉取正确的文件,它只是不提供文件保存对话框。但是,如果我从我的C#页面加载方法调用此方法并使用静态statusID进行测试,它就可以正常工作。
这里是C#方法:
public void Get_Attachment_By_StatusID(int statusID)
{
SqlDataReader _reader = null;
string _connString = "Data Source=133.31.32.33;Initial Catalog=Reports;Integrated Security=True";
string sql = "SELECT a.StatusID ,a.DocumentName ,a.MIMETypeID ,a.Binary ,a.CreatedDate ,a.CreatedBy " +
",b.MIMEType FROM Attachments a Inner join MIME_Types b on a.MIMETypeID = b.ID " +
"WHERE [StatusID] = {0} ";
sql = string.Format(sql, statusID);
try
{
_connection = new SqlConnection(_connString);
_connection.Open();
using (SqlCommand cmd = new SqlCommand(sql, _connection))
{
cmd.CommandType = System.Data.CommandType.Text;
_reader = cmd.ExecuteReader();
if (_reader.HasRows)
{
while (_reader.Read())
{
System.Web.HttpContext.Current.Response.ClearContent();
System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
System.Web.HttpContext.Current.Response.ContentType = _reader["MIMEType"].ToString();
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + _reader["DocumentName"].ToString() + ";");
byte[] b = (byte[])_reader["Binary"];
System.Web.HttpContext.Current.Response.BinaryWrite(b);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.Close();
}
}
_reader.Close();
_connection.Close();
}
}
catch (Exception ex)
{
//Log exception to error Logging app
string err = ex.ToString();
}
finally
{
if (_connection != null)
_connection.Close();
if (_reader != null)
_reader.Close();
}
}
这里是如何我从我的页面调用它,在javascript:
function GetFile(statusID) {
var url = '/Home/Get_Attachment_By_StatusID';
$.ajax({
url: url,
type: 'post',
cache: false,
data: JSON.stringify({ "statusID": statusID }),
contentType: 'application/json',
success: function (data) {
}
});
}
什么也没有发生。在Chrome浏览器中,我没有在JavaScript控制台中看到任何内容,而在IE中,我的控制台吐露了这些:“XML5619:错误的文档语法。”
再一次,如果我进入控制器,并调用我的页面加载方法的方法,它会显示保存文件对话框,并保存文件就好了。所以我一定是做错了我的javascript/jquery/ajax ...
我是新来的MVC4,知道我在这里失去了一些东西。我错过了什么?
为什么要发送J SON到URL?它是否与“正常”POST查询字符串?尝试使用'data:{statusID:statusID}'(并丢失'contentType')。 –
我会改变你的行动来接受GET请求,而不是'POST',并简单地改变你的客户端上的代码来做'window.location = path/to/action_to_download_file /;' – Icarus
@Rocket Hazmat,statusID得到那里很好,字节数组填充了正确的文件。 – codesforcoffee