这里就不说效果图了,因为我会把所有的代码,包括页面代码都贴出来,希望大家理解!首先看一下页面的代码
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FileImg.aspx.cs" Inherits="FileUpLoadImg.FileImg" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>文件上传</title>
<style type="text/css">
#form1
{
height: 973px;
}
</style>
<script language="javascript" type="text/javascript">
function ImgFile() {
return confirm("是否上传"); <!--js选择控件-->
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div style="width:49%; height:395px; float:left; background-color:White;">
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Label
ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
<div style="width:50%; height:400px; float:right; background-color:White">
<asp:Button ID="Button1" runat="server" Text="图片上传" onclick="Button1_Click" OnClientClick="ImgFile()" />
</div>
</form>
</body>
</html>
就放置了一个文件上传的空间和一个图片上传的按钮,写了一个Js的提示框!调用写的js的代码!下面我们看一下后台的代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.DataAccess;
using System.Data;
namespace FileUpLoadImg
{
public partial class FileImg : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Boolean fileOk = false;
String path = Server.MapPath("/Img/");
if(FileUpload1.HasFile)
{
String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower();//转换成为小写
String[] allowedExtensions = {".gif",".png",".jpg",".jpeg"};
for (int i = 0; i < allowedExtensions.Length; i++)
{
if (fileExtension == allowedExtensions[i])
{
fileOk = true;//判断文件上传的格式
}
}
}
if (fileOk)
{
try
{
FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName);
Label1.Text = "上传成功";
}
catch (Exception e2)
{
Label1.Text = "上传失败";
}
}
else
{
Label1.Text = "文件类型不符";
}
}
}
}
后天代码也很简单,首先我写了一个判断上传是否成功的Boolean 变量,用来判断图片是否上传成功!path 表示图片上传的路径,FileUpload1.HasFile 表示是否存在上传的文件,如果是真的话,就执行上传的代码
fileExtension 获得图片的路径 allowedExtensions数组用来判断图片上传是否满足格式要求