如何将图像上传到文件系统?
答案 0 :(得分:1)
例如(从链接的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(其他问题上引用了更多答案,这是一个热门话题)的答案中有一些选项。与往常一样,服务器端验证是必要的,即使仍然建议客户端验证用于良好的UX。从不隐含地信任客户端验证,也始终验证服务器上的用户输入。
答案 1 :(得分:1)
以下是代码示例:
你的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)