How do I change this bit of code so that I only allow pdf files to be uploaded:
如何更改这段代码,以便我只允许上传pdf文件:
unless @file.content_type =~ /^image/
errors.add(:file, "is not a recognized format")
return false
end
3 个解决方案
#1
Haven't used that, but the pdf mime type is application/pdf, so it should be just:
没用过,但pdf mime类型是application / pdf,所以应该只是:
unless @file.content_type =~ /^application\/pdf$/
#2
Of course that code is horribly insecure. It relies on the browser sending the file to get the MIME type correct and assumes no-one has send a hacked request.
当然,这段代码非常不安全。它依赖于浏览器发送文件以获得正确的MIME类型,并假设没有人发送被黑客入侵的请求。
Frankly unless you open the file and parse it, knowing what makes a valid file for a particular format you cannot be sure that any file uploaded is of a particular type.
坦率地说,除非你打开文件并解析它,知道什么是特定格式的有效文件,你不能确定上传的任何文件是特定类型。
#3
You've going to have to:
你必须:
- Accept the upload;
- Try and open the PDF in some library;
- Reject the file if you can't open it.
接受上传;
尝试在某个库中打开PDF;
如果无法打开文件,请拒绝该文件。
You can't rely on the MIME type the browser gives you. The only way to do this is to verify the file. You can check the format with markers and the like but the easiest and most robust method is to open it with an appropriate library call.
您不能依赖浏览器为您提供的MIME类型。唯一的方法是验证文件。您可以使用标记等检查格式,但最简单,最强大的方法是使用适当的库调用打开它。
#1
Haven't used that, but the pdf mime type is application/pdf, so it should be just:
没用过,但pdf mime类型是application / pdf,所以应该只是:
unless @file.content_type =~ /^application\/pdf$/
#2
Of course that code is horribly insecure. It relies on the browser sending the file to get the MIME type correct and assumes no-one has send a hacked request.
当然,这段代码非常不安全。它依赖于浏览器发送文件以获得正确的MIME类型,并假设没有人发送被黑客入侵的请求。
Frankly unless you open the file and parse it, knowing what makes a valid file for a particular format you cannot be sure that any file uploaded is of a particular type.
坦率地说,除非你打开文件并解析它,知道什么是特定格式的有效文件,你不能确定上传的任何文件是特定类型。
#3
You've going to have to:
你必须:
- Accept the upload;
- Try and open the PDF in some library;
- Reject the file if you can't open it.
接受上传;
尝试在某个库中打开PDF;
如果无法打开文件,请拒绝该文件。
You can't rely on the MIME type the browser gives you. The only way to do this is to verify the file. You can check the format with markers and the like but the easiest and most robust method is to open it with an appropriate library call.
您不能依赖浏览器为您提供的MIME类型。唯一的方法是验证文件。您可以使用标记等检查格式,但最简单,最强大的方法是使用适当的库调用打开它。