【发布时间】:2011-03-29 00:10:42
【问题描述】:
如何将图像上传到文件系统?
【问题讨论】:
标签: asp.net
如何将图像上传到文件系统?
【问题讨论】:
标签: asp.net
这是代码示例:
你的html:
<input type="file" name="Pic_0001">
注意:html 输入控件必须位于表单内
现在你的 asp .net 代码:
'this is your file name at html page
Dim HtmlFilename As String = "Pic_0001"
'the place to manipulate all uploaded files
Dim collection As System.Web.HttpFileCollection
collection = Page.Request.Files
'for example, you have selected a picture file named hotdog.jpg in browser
'this variable will manipulate your hotdog.jpg file
Dim UploadedFile As System.Web.HttpPostedFile
'retrieve the reference to your file
UploadedFile = collection.Item(HtmlFilename)
'this is the location to save your uploaded file
Dim WhereToSave As String = "c:\test folder\hotdog.jpg"
'this is your folder that will contain the uploaded file
Dim Folderpath As String = System.IO.Path.GetDirectoryName(WhereToSave)
'now do checking if the folder exists, if not create the folder
'NOTE: this step is needed to prevent folder not exists error
If System.IO.Directory.Exists(Folderpath) = False Then
System.IO.Directory.CreateDirectory(Folderpath)
End If
'now actually save your file to the server
UploadedFile.SaveAs(WhereToSave)
【讨论】:
例如(根据链接的 MSDN 文章修改),如果您只想要一个简单的表单,将文件上传到服务器上的路径,您可以从以下内容开始:
<%@ Page Language="C#" %>
<script runat="server">
protected void UploadFileAction_Click(object sender, EventArgs e)
{
var fileStoragePath = Server.MapPath("~/Uploads");
if (fileUploader.HasFile)
{
fileUploader.SaveAs(Path.Combine(fileStoragePath, fileUploader.FileName));
outputLabel.Text = string.Format(
"File Name: {0}<br />File Size: {1}kb<br />Content Type: {2}",
fileUploader.PostedFile.FileName,
fileUploader.PostedFile.ContentLength,
fileUploader.PostedFile.ContentType
);
}
else
outputLabel.Text = "You have not specified a file.";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Upload A File</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:FileUpload ID="fileUploader" runat="server" /><br />
<br />
<asp:Button ID="uploadFileAction" runat="server" OnClick="UploadFileAction_Click" Text="Upload File" /> <br />
<br />
<asp:Label ID="outputLabel" runat="server"></asp:Label></div>
</form>
</body>
</html>
FileUpload 控件最终在客户端呈现为一个简单的<input type="file" />(当然,设置了更多属性),作为整体 ASP.NET 表单元素管理的一部分,就像任何其他服务器端表单控件一样.
在您的问题中,您特别提到了上传“图片”。虽然这段代码可能会让您到达那里,但您也可能会隐含地问第二个问题,即“我如何确保上传的文件是图像?”如果是这样,您可以在this question 和this one 的答案中很好地概述了一些选项(它指的是其他问题的更多答案,这是一个热门话题)。与往常一样,服务器端验证是必要的,即使客户端验证仍被推荐用于良好的用户体验。永远不要隐式信任客户端验证,还要始终验证服务器上的用户输入。
【讨论】: