asp.net 图像 jpeg 无法正确保存
我正在尝试将 jpeg 图像保存在具有正确权限设置的上传文件夹中。当我测试正在保存文件时(例如:images/uploads/Winter.jpg),但如果我尝试在浏览器中查看图像,或者尝试使用其他任何内容打开图像,则图像不会显示。
我认为该文件在保存到磁盘之前没有被正确编码,但我在处理文件保存和编码方面经验不足。下面的代码看起来没问题,还是我需要在将上传的文件保存到磁盘之前以某种方式对其进行编码?
String imgPath = "newsletter\\images\\uploads\\";
String filename = System.IO.Path.GetFileName(upload.PostedFile.FileName);
filepath = imgPath + filename;
filepath = Request.PhysicalApplicationPath + filepath;
upload.PostedFile.SaveAs(filepath);
文件保存到正确的文件夹,但大小仅为 150 字节。如果我尝试浏览该文件并使用图像查看器查看它,则它无法正确显示。
I am trying to save a jpeg image in an uploads folder which has correct permissions setup. When I test the file is being saved (eg: images/uploads/Winter.jpg) but if I try to view the image in my browser or if I attempt to open the image using anything else the image does not display.
I think that the file is not being encoded correctly before saving it to disk but am not very experienced dealing with the saving of files, encoding. Does the below code look ok or do I need to encode the file being uploaded somehow before saving it to disk?
String imgPath = "newsletter\\images\\uploads\\";
String filename = System.IO.Path.GetFileName(upload.PostedFile.FileName);
filepath = imgPath + filename;
filepath = Request.PhysicalApplicationPath + filepath;
upload.PostedFile.SaveAs(filepath);
The file saves to the correct folder but is only 150bytes in size. If I try to browse to the file and view it with an image viewer it does not display correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
编码不应该成为问题——原始数据不会改变。但是,浏览器可能没有发送所有数据,或者上传控件在保存数据之前删除了数据。
确保在页面开始卸载之前以及任何其他回发之前调用 .SaveAs()。我认为我们需要查看更多周围的代码来提供进一步的帮助。
另一个注意事项 - 通过允许使用现有的文件扩展名,您将允许用户上传 .aspx 文件,随后可以通过请求执行该文件。安全文件名是 GUID 和列入白名单的文件扩展名。使用未经清理的上传路径信息是非常危险的。如果重复使用文件名,请将其清理为字母数字。
Encoding shouldn't be a problem - the raw data isn't changing. However, it's possible the browser isn't sending all the data, or that the upload control is deleting the data before you're saving it.
Make sure that you call .SaveAs() before the page begins unloading, and before any additional postbacks. I think we'll need to see more surrounding code to help further.
Another note - by allowing the existing file extension to be used, you're allowing users to upload .aspx files, which could subsequently be executed through a request. Safe filenames are GUIDs and whitelisted file extensions. Using un-sanitized uploaded path information is very dangerous. If you re-use filenames, sanitize them to alphanumerics.