本文介绍了在c#中验证文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我如何验证上传的文件类型?我只想让人们只上传他们的图像文件类型。



以下是我用来允许用户上传文件的代码片段:



private void StartUpLoad()

{

string companyID = this.Label1.Text;



string imgName = FileUpload1.FileName;



string imgPath =〜/ Uploads /+ imgName;



int imgSize = FileUpload1.PostedFile.ContentLength;



if(FileUpload1.PostedFile!= null && FileUpload1.PostedFile.FileName !=)

{



if(FileUpload1.PostedFile.ContentLength> 1000000)

{

Page.ClientScript.RegisterClientScriptBlock(typeof(Page),Alert,alert('File is too big。'),true);

}

其他

{



FileUpload1.SaveAs(Server.MapPath(imgPath) ));

Image1.ImageUrl = imgPath;

Page.ClientScript.RegisterClientScriptBlock(typeof(Page),Alert,alert('Image saved!') ,true);



byte [] theImage = new byte [FileUpload1.PostedFile.ContentLength];

HttpPostedFile Image = FileUpload1.PostedFile;

Image.InputStream.Read(theImage,0(int)FileUpload1.PostedFile.ContentLength);



int length = theImage.Length;

string fileName = FileUpload1.FileName.ToString();

string type = FileUpload1.PostedFile.ContentType;



int size = FileUpload1.PostedFile.ContentLe ngth;

if(FileUpload1.PostedFile!= null && FileUpload1.PostedFile.FileName!=)

{



WP_advBLL canwork = new WP_advBLL();

canwork.ExecuteInsert(theImage,type,size,fileName,length,companyID);

Response.Write(文件已成功上传!);

}

}



}



任何想法如何添加以检查所选文件的类型?

Hello, how do i validate the file types that are uploaded ? i only want to allow people to upload their image file types only.

Below is a snippet of code that i use to allow users to upload their file:

private void StartUpLoad()
{
string companyID = this.Label1.Text;

string imgName = FileUpload1.FileName;

string imgPath = "~/Uploads/" + imgName;

int imgSize = FileUpload1.PostedFile.ContentLength;

if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{

if (FileUpload1.PostedFile.ContentLength > 1000000)
{
Page.ClientScript.RegisterClientScriptBlock(typeof(Page), "Alert", "alert('File is too big.')", true);
}
else
{

FileUpload1.SaveAs(Server.MapPath(imgPath));
Image1.ImageUrl = imgPath;
Page.ClientScript.RegisterClientScriptBlock(typeof(Page),"Alert","alert('Image saved!')", true);

byte[] theImage = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile Image = FileUpload1.PostedFile;
Image.InputStream.Read(theImage,0(int)FileUpload1.PostedFile.ContentLength);

int length = theImage.Length;
string fileName = FileUpload1.FileName.ToString();
string type = FileUpload1.PostedFile.ContentType;

int size = FileUpload1.PostedFile.ContentLength;
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
{

WP_advBLL canwork = new WP_advBLL();
canwork.ExecuteInsert(theImage, type, size, fileName, length,companyID);
Response.Write("File has been uploaded successfully!");
}
}

}

Any idea how to add on to check for type of files selected?

推荐答案



这篇关于在c#中验证文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 06:05