English 中文(简体)
How to upload and download file from a server using C#
原标题:

I am developing a webpage in that the user can download their Resume for Edit. So I have a link to download the article. I use the following code for download.

DataTable dt = user.getUserDetails(2);
user.WriteFileFromDBbyUserArticleID(Server.MapPath(Convert.ToString(dt.Rows[0].ItemArray[0])), Convert.ToInt32(2), "CV");
FileUtil.writeFileToResponse(Server.MapPath(Convert.ToString(dt.Rows[0].ItemArray[0])), Response);

////////////////////////////////////////////////
public void WriteFileFromDBbyUserArticleID(string FilePath, int UserID, string FileType)
{
    DataAccessLayer dal = new DataAccessLayer();

    string selectQuery = "Select Articles.Users_WriteFileFromDB(?,?,? ) from Articles.Users";

    DbParameter[] parm = new DbParameter[3];
    parm[0] = dal.GetParameter();
    parm[0].ParameterName = "@FilePath";
    parm[0].Value = FilePath;

    parm[1] = dal.GetParameter();
    parm[1].ParameterName = "@UserID";
    parm[1].Value = UserID;

    parm[2] = dal.GetParameter();
    parm[2].ParameterName = "@FileType";
    parm[2].Value = FileType;

    DataTable dtArticleStatus = dal.ExecuteDataTable(selectQuery, parm);
}

///////////////////////////////////////////////////////////////////////////
static public void writeFileToResponse(string filePath,HttpResponse Response)
{
    try
    {
        string FileName = Path.GetFileName(filePath);
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);
        Response.WriteFile(filePath);
        Response.Flush();
        File.Delete(filePath);
        Response.End();
    }
        catch (System.Exception ex)
    {
    }
}

I got the error in the line "Response.WriteFile(filePath);" as follows

sys.webforms.pagerequestManagerparserErrorException: The message received from the server could not be parsed. Common causes for this error are when the response is modified by calls to response.write(), response filters, httpModules, or server trace is enabled. Details:Error parsing near ...

How do I fix this?

最佳回答
public class FileHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        if (context.Request["file"] != null)
        {
            try
            {
                string file = context.Server.MapPath("~/files/" + context.Request["file"].ToString());
                FileInfo fi = new FileInfo(file);
                if (fi.Exists)
                {
                    context.Response.ClearContent();
                    context.Response.AddHeader("Content-Disposition", "attachment; filename=" + fi.Name);
                    context.Response.AddHeader("Content-Length", fi.Length.ToString());
                    string fExtn = "video/avi";
                    context.Response.ContentType = fExtn;
                    context.Response.TransmitFile(fi.FullName);
                    context.Response.End();
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.Message);
            }
        }
    }

    public bool IsReusable
    {
        get { return true; }
    }
}
问题回答

You can stream the document back using Response stream.

This might get you going.

Response

Request, Response Objects

Are you using ASP.NET? Try HtmlInputFile for the uploads.

http://www.codeproject.com/KB/aspnet/fileupload.aspx

For uploading file you can use asp:FileUpload control and simple use SaveAs method. But be aware that if you use it in combination with partial update object (asp:UpdatePanel) that you ll allso have to set triggers. If you don t use triggers asp:FileUpload control can be resetted...





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签