asp.net 使用C#下载存储在SQL DB上的文件

wi3ka0sx  于 2023-02-01  发布在  .NET
关注(0)|答案(1)|浏览(174)

我使用以下脚本上传PDF文件并将其存储在SQL数据库中:

public partial class upload : System.Web.UI.Page
{
    string GetServerFilenext(string strFileFullPath)
    {
        string strFileToCheck = "";
        for (int i = 0; i < 100; i++)
        {
            if (i == 0)
                strFileToCheck = strFileFullPath;
            else
                strFileToCheck =
                    Path.GetDirectoryName(strFileFullPath) +
                    @"\" + Path.GetFileNameWithoutExtension(strFileFullPath) +
                    "-" + i.ToString() + Path.GetExtension(strFileFullPath);

            if (!File.Exists(strFileToCheck))
                break;
        }
        return strFileToCheck;
    }

    DataBaseDataContext dataBaseDataContext = new DataBaseDataContext();
    private string path;

    protected void Page_Load(object sender, EventArgs e)
    {
    }

    protected void btnExit_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

    protected void SUbmit(object sender, EventArgs e)
    {
        try
        {
            var ext = FileUploadtoServer.FileName.Substring(FileUploadtoServer.FileName.IndexOf('.') + 1, 3);
            if (ext.ToLower() != "pdf")
            {
                Response.Write("<script>alert('Please select a pdf File!')</script>");
                return;
            }
        }
        catch (Exception)
        {
            Response.Write("<script>alert('Please select a pdf File!')</script>");
            return;
        }

        if (PO_Number.Text.Equals("") || HeadCode.Text.Equals("") || Manufacture.Text.Equals("") || Description.Text.Equals("") || Invoice.Text.Equals(""))
        {
            Response.Write("<script>alert('Please Fill All Fields!')</script>");
        }

        string sFileToSave =
       Server.MapPath(@"~/Attachments/" + PO_Number.Text + Invoice.Text + ".pdf");

        sFileToSave = GetServerFilenext(sFileToSave);

        TPT TPT = new TPT();
        TPT.Invoice_No = Invoice.Text;
        TPT.PO_Number = PO_Number.Text;
        TPT.Item_Code = Manufacture.Text;
        TPT.Heat_Code = HeadCode.Text;
        TPT.Description = Description.Text;
        TPT.FileName = Path.GetFileName(sFileToSave);
        dataBaseDataContext.TPTs.InsertOnSubmit(TPT);
        dataBaseDataContext.SubmitChanges();

       
        FileUploadtoServer.SaveAs(sFileToSave);

        Response.Write("<script>alert('Successfully Inserted!')</script>");
        Invoice.Text = "";
        Manufacture.Text = "";
        HeadCode.Text = "";
        Description.Text = "";
        PO_Number.Text = "";
    }

}

当我想下载上传的信息时,我使用以下脚本跟踪文档。此脚本从SQL表下载错误的pdf,而不是与记录关联的文件名。

public partial class track : System.Web.UI.Page
{
    DataBaseDataContext dataBaseDataContext = new DataBaseDataContext();
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    private void BindData(List<TPT> Data)
    {
        try
        {
            if (Data.Count > 0)
            {
                StringBuilder append = new StringBuilder();
                foreach (TPT TPT in Data)
                {
                    string PdfName = TPT.FileName;
                    append.Append("<tr><td><a style=\"color:blue;\" href=\"#\" onclick=\"doPop('" + TPT.id + "');\">Edit / Download</a></td><td>" + TPT.Heat_Code + "</td><td>" + TPT.Item_Code + "</td><td>" + TPT.PO_Number + "</td><td>" + TPT.Description + "</td><td>" + TPT.Invoice_No + "</td></tr>");
                }
                tdList.InnerHtml = append.ToString();
            }
        }
        catch (Exception)
        {
        }
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (!HeatCode.Text.Equals(""))
        {
            DataBaseDataContext model = new DataBaseDataContext();

            var query = model.TPTs.AsQueryable();
            if (!string.IsNullOrEmpty(this.HeatCode.Text))
            {

                query = (from Schl in model.TPTs
                         where
                         Schl.Heat_Code.Equals(HeatCode.Text)
                         orderby Schl.Heat_Code
                         select Schl);
            }
            List<TPT> List = query.ToList();
            if (List.Count > 0)
            {
                BindData(List);
            }
            else
            {
                Response.Write("<script>alert('No Record Found!')</script>");
            }
        }
        else if (!Item_Code.Text.Equals(""))
        {
            DataBaseDataContext model = new DataBaseDataContext();

            var query = model.TPTs.AsQueryable();
            if (!string.IsNullOrEmpty(this.Item_Code.Text))
            {

                query = (from Schl in model.TPTs
                         where
                          Schl.Item_Code.Equals(Item_Code.Text)
                         orderby Schl.Item_Code
                         select Schl);
            }
            List<TPT> List = query.ToList();
            if (List.Count > 0)
            {
                BindData(List);
            }
            else
            {
                Response.Write("<script>alert('No Record Found!')</script>");
            }
        }
        else if (!PO_Number.Text.Equals(""))
        {
            DataBaseDataContext model = new DataBaseDataContext();

            var query = model.TPTs.AsQueryable();
            if (!string.IsNullOrEmpty(this.PO_Number.Text))
            {

                query = (from Schl in model.TPTs
                         where
                          Schl.PO_Number.Equals(PO_Number.Text)
                         orderby Schl.PO_Number
                         select Schl);
            }
            List<TPT> List = query.ToList();
            if (List.Count > 0)
            {
                BindData(List);
            }
            else
            {
                Response.Write("<script>alert('No Record Found!')</script>");
            }
        }
        else if (!Description.Text.Equals(""))
        {
            DataBaseDataContext model = new DataBaseDataContext();

            var query = model.TPTs.AsQueryable();
            if (!string.IsNullOrEmpty(this.Description.Text))
            {

                query = (from Schl in model.TPTs
                         where
                          Schl.Description.StartsWith(Description.Text)
                         orderby Schl.Description
                         select Schl);
            }
            List<TPT> List = query.ToList();
            if (List.Count > 0)
            {
                DataBaseDataContext db = new DataBaseDataContext();
                var listitemsrecord = (from Schl in db.TPTs
                                       where
                                       Schl.Description.Contains(Description.Text)
                                       orderby Schl.Heat_Code
                                       select Schl).ToList();
                BindData(listitemsrecord);
            }
            else
            {
                Response.Write("<script>alert('No Record Found!')</script>");
            }
        }
        else
        {
            Response.Write("<script>alert('Fields are Empty!')</script>");
        }
    }
    protected void btnClear_Click(object sender, EventArgs e)
    {
        HeatCode.Text = string.Empty;
        Item_Code.Text = string.Empty;
        PO_Number.Text = string.Empty;
        tdList.InnerHtml = string.Empty;
        Description.Text = string.Empty;
    }
    protected void btnExit_Click(object sender, EventArgs e)
    {
        Response.Redirect("default.aspx");
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            byte[] content = File.ReadAllBytes(Server.MapPath(@"~/Attachments/" + txtPONum.Text + txtInvoice.Text + ".pdf"));
            Response.ContentType = "text/pdf";
            Response.AddHeader("content-disposition", "Attachments; filename=" + txtPONum.Text + txtInvoice.Text + ".pdf");
            Response.BufferOutput = true;
            Response.OutputStream.Write(content, 0, content.Length);
            Response.End();    
        }
        catch (Exception)
        {
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (CheckAvailability())
        {
            Boolean file = true;
            try
            {
                var ext = FileUploadtoServer.FileName.Substring(FileUploadtoServer.FileName.IndexOf('.') + 1, 3);
                if (ext.ToLower() != "pdf")
                {

                    file = false;
                }
            }
            catch (Exception ex)
            {

                file = false;

            }
            TPT m = (from p in dataBaseDataContext.TPTs
                     where p.id ==Convert.ToInt32(hid.Value)
                     select p).SingleOrDefault();

            if (file)
            {
                File.Delete(Server.MapPath(@"~/Attachments/" + m.FileName));
                String path = Server.MapPath(@"~/Attachments/" + txtPONum.Text + txtInvoice.Text + ".pdf");
                m.FileName = txtPONum.Text + txtInvoice.Text + ".pdf";
                FileUploadtoServer.SaveAs(path);
            }
            m.Invoice_No = txtInvoice.Text;
            m.PO_Number = txtPONum.Text;
            m.Item_Code = txtItemCode.Text;

            m.Description = txtDesc.Text;
            dataBaseDataContext.SubmitChanges();

            Response.Write("<script>alert('Updated!');window.location='track.aspx';</script>");
        }
        else
        {
            Response.Write("<script>alert('No Record Found For This Data!')</script>");
        }
    }

    public Boolean CheckAvailability()
    {
        var checkinPrimaryKey = (from x in dataBaseDataContext.TPTs where x.id.Equals(hid.Value) select x).ToList<TPT>();
        if (checkinPrimaryKey.Count > 0)
        {
            return true;
        }
        return false;
    }
}

我想问题可能出在上传的文件路径上。但是,我从相同的上传位置提取了文件路径进行下载。是否有其他方法可以实现这一点?

polhcujo

polhcujo1#

嗯,你可以试试这个代码:

string strInternalFile = "";   // VALID full windows style path name

        if (File.Exists(strInternalFile))
        {
            FileInfo iFileInfo = new FileInfo(strInternalFile);
            string strConType = MimeMapping.GetMimeMapping(strInternalFile);

            Response.Clear();
            Response.ContentType = strConType;
            Response.AppendHeader("Content-Length", iFileInfo.Length.ToString());
            Response.AppendHeader("Content-Disposition", "attachment; filename="
                + Path.GetFileName(strInternalFile));
            Response.TransmitFile(strInternalFile);
            Response.End();

        }
        else
        {
            Response.Write(@"<h3>File not found</h3>");
        }

所以,它不清楚,如果文件不存在???
但是,我有更好的运气使用内置的TransmistFile,而不是使用说输出流。
此外,“GetMine Mapping”需要.net 4.5或更高版本。

相关问题