第三章:与AspUpload协作

基于浏览器的文件上传

在很多真实的应用中,比如说在线相册,在图像被重置尺寸之前,它必须先由用户上传到Web服务器上。为了捕获上传的图像,必须使用一个服务器端上传组件,比如说Persits软件公司的AspUpload ®组件。AspJpeg可以与任何上传组件串联使用,并不仅限于AspUpload,但是我们的讨论和代码示例将基于AspUpload。要想了解更多关于AspUpload的信息,并下载30天评估版副本,请访问www.aspupload.com

从用户的机器把一个或多个文件上传到服务器,可以使用元素属性ENCTYPE="multipart/form-data"的<FORM>表单,以及一个或多个<INPUT TYPE="FILE">表单项。要想捕获上传的文件,并用AspUpload把它们保存在服务器上,可以使用的方法之一如下所示:

<FORM ENCTYPE="multipart/form-data" ACTION="upload.asp" METHOD="POST">
   <INPUT TYPE="FILE" NAME="FILE1">
   <INPUT TYPE="FILE" NAME="FILE2">
   <INPUT TYPE="FILE" NAME="FILE3">
   <INPUT TYPE="SUBMIT" VALUE="Upload!">
</FORM>

upload.asp:

<% 
Set Upload = Server.CreateObject("Persits.Upload")
' Save uploaded files
Upload.Save "c:\upload"

' Display paths of uploaded files
For Each File in Upload.Files
   Response.Write File.Path & "<BR>"
Next

%>

除了使用HTML表单,文件还可以使用多种第三方客户端ActiveX控制和Java小程序上传到服务器,Java小程序能够提供表单中没有的额外功能,比如说上传整个目录的能力,或者拖放上传的能力。这些产品超出了本讨论的范围,我们只关注于服务器端脚本。欲知更多关于客户端上传代理XUpload和JUpload的信息,参见AspUpload.com网站。

缩放上传的图像

以下代码示例使你能够上传一个图像,缩放它,然后把原始图像和它的缩略图保存在MS Access数据库文件aspjpeg.mdb中。注意,这段代码示例把缩略图保存到磁盘,然后重新打开它以实现数据库保存。直接的内存到数据库的程序在第三章第三节中讲解。

在运行代码示例之前,请确保AspUpload已经安装在你的服务器上,并使用Windows资源管理器给“Everyone”用户组对数据库文件aspjpeg.mdb完全的控制权,否则会在上传过程中会发生一个运行时错误,该数据库文件位于子目录\Samples\DB\。

VB Script:

<%
' Create an instance of AspUpload object
Set Upload = Server.CreateObject("Persits.Upload")
' Compute path to save uploaded files to
Path = Server.MapPath(".")

' Capture uploaded file. Return the number of files uploaded
Count = Upload.Save(Path)

If Count = 0 Then
  Response.Write "No images selected."
  Response.End
Else
  ' Obtain File object representing uploaded file
  Set File = Upload.Files(1)

  ' Is this a valid image file?
  If File.ImageType <> "UNKNOWN" Then

    ' Create instance of AspJpeg object
    Set jpeg = Server.CreateObject("Persits.Jpeg")

    ' Open uploaded file
    jpeg.Open( File.Path )

    ' Resize image according to "scale" option.
    ' We cannot use Request.Form, so we use Upload.Form instead.
    jpeg.Width = jpeg.OriginalWidth * Upload.Form("scale") / 100
    jpeg.Height = jpeg.OriginalHeight * Upload.Form("scale") / 100

    SavePath = Path & "\small_" & File.ExtractFileName

    ' AspJpeg always generates thumbnails in JPEG format.
    ' If the original file was not a JPEG, append .JPG ext.
    If UCase(Right(SavePath, 3)) <> "JPG" Then
      SavePath = SavePath & ".jpg"
    End If

    jpeg.Save SavePath

    ' Save both images in the database along with description.
    strConnect = "DRIVER={Microsoft Access Driver (*.mdb)};DBQ=" & Server.MapPath("../db/aspjpeg.mdb")

    Set rs = Server.CreateObject("adodb.recordset")
    rs.Open "images", strConnect, 1, 3
    rs.AddNew

    ' Use File.Binary to access binary data of uploaded file.
    rs("original_image").Value = File.Binary
    Set ThumbFile = Upload.OpenFile(SavePath)
    rs("thumbnail").Value = ThumbFile.Binary
    rs("description") = Upload.Form("Description")
    rs.Update
    rs.Close
    Set rs = Nothing

    Response.Write "Success!"
  Else
    Response.Write "This is not a valid image."
    Response.End
  End If
End If
%>

C#:

<script runat="server" LANGUAGE="C#">
void Page_Load(Object Source, EventArgs E)
{
// Create an instance of AspUpload object
IUploadManager objUpload;
objUpload = new UploadManager();

String strPath = Server.MapPath(".");

// Save returns the number of uploaded files
int nCount = objUpload.Save(strPath, Missing.Value, Missing.Value);

if( nCount == 0 )
{
  txtMsg.InnerHtml = "No images selected.";
  return;
}

// Obtain File object representing uploaded file
IUploadedFile objFile;
objFile = objUpload.Files.Item(1);

// Is this a valid image file?
if( objFile.ImageType != "UNKNOWN" )
{
  // Create instance of AspJpeg object
  IASPJpeg objJpeg;
  objJpeg = new ASPJpeg();

  // Open uploaded file
  objJpeg.Open( objFile.Path );

  // Resize image according to "scale" option.
  // We cannot use Request.Form, so we use Upload.Form instead.
  int nScale = int.Parse(objUpload.Form.Item("scale").Value);
  objJpeg.Width = objJpeg.OriginalWidth * nScale / 100;
  objJpeg.Height = objJpeg.OriginalHeight * nScale / 100;

  String strSavePath = strPath + "\\small_" + objFile.ExtractFileName();

  // AspJpeg always generates thumbnails in JPEG format.
  // If the original file was not a JPEG, append .JPG extension.
  if( strSavePath.ToUpper().Substring( strSavePath.Length - 3) != "JPG" )
  {
    strSavePath += ".jpg";
  }

  objJpeg.Save( strSavePath );

  // Save both images in the database along with description.
  String strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + Server.MapPath("../db/aspjpeg.mdb");
  OleDbConnection myConnection = new OleDbConnection(strConn);
  myConnection.Open();

  OleDbDataAdapter myDataAdapter = new OleDbDataAdapter ("select * from images", myConnection);
  DataSet myDataSet = new DataSet();
  myDataAdapter.Fill( myDataSet, "images" );

  DataTable tblImages = myDataSet.Tables["images"];
  DataRow rowImage;

  // Add a new row
  rowImage = tblImages.NewRow();
  tblImages.Rows.Add( rowImage );

  rowImage.BeginEdit();

  // Save original image and thumbnail in the database table.
  rowImage["original_image"]    = objFile.Binary;
  IUploadedFile objThumb = objUpload.OpenFile( strSavePath );
  rowImage["thumbnail"] = objThumb.Binary;
  rowImage["description"] = objUpload.Form.Item("description").Value;
  rowImage.EndEdit();

  // Without this line, Update will fail.
  OleDbCommandBuilder myCB = new OleDbCommandBuilder(myDataAdapter);
  myDataAdapter.Update( myDataSet, "images" );

  myConnection.Close();
  txtMsg.InnerHtml = "Success!";
}
else
{
  txtMsg.InnerHtml = "This is not a valid image.";
}
}
</script>

点击以下链接以运行该代码示例:

http://localhost/aspjpeg/manual_03/03_form.asp

http://localhost/aspjpeg/manual_03/03_form.aspx

内存上传

AspUpload能够把上传的文件保存到内存中,而不是保存到磁盘中。因为AspJpeg可能 从内存中打开图像,而且还可以把结果缩略图保存到内存中,这整个“上传→缩放大小→保存到数据库”的处理可以一气呵成地实施,不在服务器的硬盘上创建临时文件,它提升了性能,节省了服务器空间,并提高了安全性。

以下代码示例近似于前一个代码示例,除了我们使用AspUpload的内存上传功能(调用了Save方法,不带有Path参数),通过Jpeg.OpenBinary( File.Binary )方法打开了一个上传的图像,然后通过rs("image").value=Jpeg.Binary把结果缩略图直接保存到数据库记录集中:

VB Script:

<%
...
Count = Upload.Save
' Open uploaded file from memory
jpeg.OpenBinary( File.Binary )

' For now, Jpeg.Binary contains the original image
rs("original_image").Value = Jpeg.Binary
...

jpeg.Width = jpeg.OriginalWidth * Upload.Form("scale") / 100
jpeg.Height = jpeg.OriginalHeight * Upload.Form("scale") / 100

' Now Jpeg contains a resized version of the original file.
rs("thumbnail").Value = Jpeg.Binary

...
%>

C#

<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Reflection" %>
<%@ Import Namespace="ASPJPEGLib" %>
<%@ Page aspCompat="True" %>

<script runat="server" LANGUAGE="C#">

void Page_Load(Object Source, EventArgs E)
{
...

// Save to memory, return the number of uploaded files
int nCount = objUpload.Save(Missing.Value, Missing.Value, Missing.Value);
...

// objJpeg contains original image
rowImage["original_image"]    = objJpeg.Binary;

// Resize image according to "scale" option.
// We cannot use Request.Form, so we use Upload.Form instead.
int nScale = int.Parse(objUpload.Form.Item("scale").Value);
objJpeg.Width = objJpeg.OriginalWidth * nScale / 100;
objJpeg.Height = objJpeg.OriginalHeight * nScale / 100;

// Now objJpeg contains resized version of original image
rowImage["thumbnail"] = objJpeg.Binary;

...
}

</script>

点击以下链接以运行该代码示例:

http://localhost/aspjpeg/manual_03/03_form2mem.asp

http://localhost/aspjpeg/manual_03/03_form2mem.aspx

如果你喜欢这篇文章,敬请给站长打赏↑

除特别注明外,本站所有文章均为本站站长原译,转载请注明出处。