我正在尝试使用HttpFileCollection在一个文件夹中上传视频文件,但它似乎没有保存在文件夹中。尽管路径正确,但它发出的错误是找不到路径。这是我的代码
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" ImageUrl="~/ProductVideos/" runat="server" Width="118px" />
</div>
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
C#代码:
protected void Button1_Click(object sender, EventArgs e)
{
UploadVideoToFolder();
}
public string UploadVideoToFolder()
{
string vTitle = "";
string vDesc = "";
string FilePath = HttpContext.Current.Server.MapPath("~/ProductVideos/" + HttpContext.Current.Request.Form["title"]);
HttpFileCollection MyFileCollection = HttpContext.Current.Request.Files;
if (MyFileCollection.Count > 0)
{
// Save the File
try
{
MyFileCollection[0].SaveAs(FilePath);
return "1";
}
catch (Exception ex)
{
return "-1";
}
}
else
return "-1";
请帮我这样做。
答案 0 :(得分:3)
试试这段代码。
string filename = Path.GetFileName(FileUpload1.FileName);
HttpFileCollection MyFileCollection = HttpContext.Current.Request.Files;
if (MyFileCollection.Count > 0)
{
try
{
MyFileCollection[0].SaveAs(Server.MapPath("~/ProductVideos/") + filename);
}
catch (Exception ex)
{
}
}
答案 1 :(得分:0)
参考以下代码:
您必须在代码中添加for循环,如下所示:
HttpFileCollection MyFileCollection = Request.Files;
for (int i = 0; i < MyFileCollection .Count; i++)
{
HttpPostedFile httpPostedFile = MyFileCollection [i];
if (httpPostedFile.ContentLength > 0 )
{
}
}