从ASP.net页面上传图像 [英] Image uploading from ASP.net Page

查看:46
本文介绍了从ASP.net页面上传图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我正在做一个项目,陷入了一个场景.就像

我正在从WebCam和asp.net文件上传控件在asp.net页面中上传图像.
我将图像转换为字节数组,并将其存储在数据库SQL中.

现在,我们需要在网格视图中显示所有图像,并将字节数组作为Image写入Project Directory的temp文件夹中.现在,我要在离开页面时删除临时文件.

我应该在哪里编写代码(在Page的哪个事件上)
任何帮助将不胜感激.

Hi

I am working on a project and stuck in a scenario. It goes like

I am uploading an image from WebCam and asp.Net File Upload Control in a asp.net page.
I am converting the image into Byte Array and storing it in Database SQL.

Now we need to display all images in a grid View and writing the byte array as Image into temp folder of Project Directory. Now I want to delete my temporary files when I am leaving my Page.

Where Should I code for this (on which event of Page)
Any help would be appreciated.

推荐答案

您可以将图像放置在文件夹中并引用它们,但是当用户离开页面时删除它们是棘手的部分. br/>
我建议您创建一个页面,该页面将直接从数据库返回图像.您应该将它们存储为jpeg或png以提高性能.

然后创建一个名为getimage.aspx的页面.然后在Page_Load 事件中,返回图像(假设您使用ID或某种方式来检索字节),例如getimage.aspx?imageid = 123.

假设您获得了ID,并从数据库中获得了流,只需将字节写入Response.OutputStream

you can place the images in a folder and reference them, but deleting them when the user leaves the page is the tricky part.

I would recommend you to create a page that will return the images directly from the database. You should store them as jpeg or png for performance.

Then create a page called getimage.aspx or something. and there in the Page_Load event, return the image (given that you use an ID or something to retrieve the bytes) something like getimage.aspx?imageid=123 for example.

Lets say you got the id, and get the stream from the database, just write the bytes to the Response.OutputStream

Response.Clear();
Response.ContentType = "image/jpeg";
var downloadName = HttpUtility.UrlEncode("imagenameyouwant.jpg", System.Text.Encoding.UTF8);
Response.AppendHeader("content-disposition", string.Format("attachment;filename={0}{1}", downloadName, ext));
Bufferer.Send(input, Response.OutputStream, 4096);
input.Close();
Response.Flush();
Response.End();



缓冲程序是我用来发送片段内容的帮助程序类.这是Bufferer.Send方法的代码:



the bufferer is a helper class I use to send the content in fragments. here is the code for the Bufferer.Send method:

public static void Send(Stream InputBuffer, Stream OutputBuffer, int bufferSize)
   {
       if (InputBuffer == null) throw new Exception("Input buffer can not be null");
       if (InputBuffer.Position != 0)
           InputBuffer.Position = 0;

       byte[] bytes = new byte[bufferSize];
       int numBytes;
       while ((numBytes = InputBuffer.Read(bytes, 0, bufferSize)) > 0)
           OutputBuffer.Write(bytes, 0, numBytes);
   }



这种方法的好处是您不需要保存(也不必删除)图像,也不需要使用任何tmp文件夹.



This approach has the benefit that you don''t need to save (and also not delete) the images, nor use any tmp folder.


您不能,也不可靠.当用户移至新页面时,您会获得一些事件,但这并不意味着您将始终获得它们:用户浏览器崩溃,电源故障或其他几种原因之一?您的文件将被遗忘,并且可能永远不会被删除.

为什么要从数据库中将它们提取到文件中?我能想到的唯一原因是使用户易于下载它们-为什么不让用户直接从数据库下载文件呢?这样,就不会创建临时文件,因此无需清除任何内容.

我要做的是将指向apsx页面的链接设置为下载链接:
You can''t, not reliably. There are events you can get when the user moves to a new page, but that doesn''t mean that you will always gets them: what it the users browser crashes, the power fails, or one of several other reasons? Your file will get left behind, and probably never deleted.

Why are you extracting them from the database to files? The only reason I can think of is to make it easy for the user to download them - so why not let the user download the file directly from the database instead? That way, no temporary files are created, so there is nothing to clear up.

What I do is to set a link to an apsx page as the download link:
/// <summary>
/// Add a download file's information to a table row.
/// </summary>
/// <param name="dl"></param>
/// <returns></returns>
private static HtmlTableRow AddDownloadFile(Downloadable dl)
    {
    HtmlTableRow row = new HtmlTableRow();
    // File name
    HtmlTableCell cell = new HtmlTableCell();
    cell.InnerHtml = "<a href=\"FileTransferDownload.aspx?file=" + dl.Id + "\" target=\"_blank\">" + dl.FileName + "</a>";
    row.Cells.Add(cell);
    // Version
    cell = new HtmlTableCell();
    cell.InnerText = dl.Version.ToString();
    row.Cells.Add(cell);
    // Upload date
    cell = new HtmlTableCell();
    cell.InnerText = dl.UploadedOn.ToString();
    row.Cells.Add(cell);
    return row;
    }

然后页面处理工作:

And then the page handles the work:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="FileTransferDownload.aspx.cs" Inherits="FileTransferDownload" %>

<%
    // Send a download file to the client given the filename.
    string guid = Request.QueryString["file"];
    string fileName = "ERROR";
    byte[] data = new byte[] { 0, 0, 0, 0 };
    string strCon = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["DownloadDatabase"].ConnectionString;
    using (System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(strCon))
        {
        con.Open();
        string strcmd = "SELECT [iD] ,cn.[fileName],[description] ,[dataContent] ,[version] " +
                        "FROM dlContent cn " +

                        "WHERE cn.iD=@ID";
        using (System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(strcmd, con))
            {
            cmd.Parameters.AddWithValue("@ID", guid);
            using (System.Data.SqlClient.SqlDataReader r = cmd.ExecuteReader())
                {
                if (r.Read())
                    {
                    fileName = (string) r["filename"];
                    data = (byte[]) r["dataContent"];
                    }
                }
            }
        }
    Response.Clear();
    Response.AddHeader("Cache-Control", "no-cache, must-revalidate, post-check=0, pre-check=0");
    Response.AddHeader("Pragma", "no-cache");
    Response.AddHeader("Content-Description", "File Download");
    Response.AddHeader("Content-Type", "application/force-download");
    Response.AddHeader("Content-Transfer-Encoding", "binary\n");
    Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
    Response.BinaryWrite(data);
    //Response.WriteFile("wm5ftdata/" + fileName);
    Response.End();
%>


这篇关于从ASP.net页面上传图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆