问题描述
我正在尝试将图片文件上传到〜/ Pictures /。 FileUpload因为非null的imagename和ext而起作用。结果是没有图像存储在〜/ Pictures /中,没有错误消息。
I am trying to upload an image file to "~/Pictures/". The FileUpload has worked because of a non null imagename and ext. The result is no image is stored in "~/Pictures/" with no error message.
if (FileUpload1.HasFile)
{
string imagename = System.IO.Path.GetFileName(FileUpload1.FileName);
Label1.Text = imagename;
string ext = System.IO.Path.GetExtension(FileUpload1.FileName);
Label2.Text = ext;
string imagefile = Server.MapPath("Pictures/" + imagename);
byte[] Image = null;
if (ext == ".jpg" | ext == ".gif" | ext == ".png" | ext == ".bmp")
{
Image = new byte[FileUpload1.PostedFile.ContentLength];
HttpPostedFile UploadedImage = FileUpload1.PostedFile;
UploadedImage.InputStream.Read(Image, 0, (int)FileUpload1.PostedFile.ContentLength);
UploadedImage.SaveAs(imagefile);
}
}
我的尝试:
尝试文件流传输byte [] Image。
What I have tried:
Tried Filestreaming the byte[] Image.
推荐答案
string imagefile = Server.MapPath("Pictures/" + imagename);
你从中得到的路径将是相对于当前页面 - 如果你想要一个绝对路径,你需要指定根文件夹:
The path you get from that will be relative to the location of the current page - if you want an absolute path, you need to specify the root folder:
string imagefile = Server.MapPath("~/Pictures/" + imagename);
其次,正如理查德所说,你需要检查你的扩展名:C#字符串默认区分大小写,所以.JPG与.jpg不一样例如。 Windows并不关心文件名或扩展名的情况,但C#确实如此!
第三,为什么在直接通过 [] - 我不确定SaveAs方法是否会将您读取的流重新回到Image数组中。
Second, as Richard says, you need to check your extension: C# strings are by default case sensitive, so ".JPG" is not the same as ".jpg" for example. Windows doesn't care about the case on file names or extensions, but C# does!
Third, why are you reading the stream when you can just get the bytes directly via the FileUpload.FileBytes Property (System.Web.UI.WebControls)[^] - I'm not sure that the SaveAs method rewinds the stream that you read into the Image array.
这篇关于如何将文件从fileupload保存到root diectory上的文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!