将文件上传限制为某些文件扩展名 [英] Restrict file upload to some file extensions

查看:115
本文介绍了将文件上传限制为某些文件扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在上传文件时遇到问题.我想允许用户上传系统允许的文件...

I am having a problem with uploading files. I want to allow users to upload files that the system allows...

例如,我允许用户上传扩展名为 *.jpg 的文件.因此,在文件选择窗口中,他们只能看到带有 jpg 扩展名的文件.

For example, I allow files having an extension of *.jpg to be uploaded by users. So, in the file selection window they must see only files with the jpg extension.

我怎样才能在 RoR 中得到这个?

How can I get this in RoR?

推荐答案

这个问题的答案可能更多地与 html 上传而不是 rails 相关.

The answer to this question is probably more related to html uploading than rails.

当您要上传文件时,通常使用 type="file" 进行输入.

When you want to upload a file, you typically do an input with type="file".

这可以在 Rails 中使用 file_field_tag 助手.它会生成一个 type="file" 的输入,它也可以有一个 accept 属性,但你不能真正使用它,因为它不会真正产生任何可见的效果.该属性接受 MIME 类型,不接受扩展,大多数浏览器甚至不使用它.

This can be done in Rails by using the file_field_tag helper. It will generate an input with type="file" which can also have an accept attribute, but you can't really use that because it's not really going to have any visible effect. This attribute accepts MIME types, not extensions, and most browsers don't even use it.

您能做的最好的事情可能是在上传之前(在您从对话框中选择文件之后)使用 javascript 检查文件扩展名.在这个问题中阅读更多相关信息.

The best thing you can do is probably have a javascript check the file extension before upload (after you select the file from the dialog box). Read more about it in this question.

关键是,您不能强制操作系统只显示您想要的文件扩展名.例如,您可以在上传之前使用 JS 验证扩展名,也可以在上传后检查文件内容,服务器端

The point is, you can't force the OS to show you only the file extensions that you want. You can either validate the extension by using JS for example, before upload, or check the contents of the file after upload, server side

这篇关于将文件上传限制为某些文件扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆