问题
This is an odd question, but only commensurate with the strange behavior I'm seeing. My app is Rails 3/Paperclip/S3.
Symptoms:
- All images are uploading regardless of their title.
- When uploading a .pdf or .doc, if the title has no spaces like my_doc.pdf, it uploads fine.
- When uploading a .pdf or .doc with spaces, such as My Doc.pdf, it fails, either with error
broken pipe
or by the file silently failing to upload to S3. - When uploading a .pdf or .doc with numbers, such as mydoc20.pdf, it also fails as above.
I imagine there are two possible solutions to this problem.
- Fix the
broken pipe
error directly (preferred method). - Automatically rename every uploaded file to remove spaces and numbers before it is saved to S3 - while not fixing it at the source, I imagine this would allay the issue.
I would greatly appreciate any help you can give me in fixing 1 and/or 2.
Code
# Upload.rb model
class Upload < ActiveRecord::Base
has_attached_file :document,
:storage => :s3,
:s3_credentials => "#{::Rails.root.to_s}/config/s3.yml",
:path => "/docs/:style/:id/:basename.:extension"
has_attached_file :photo,
:styles => {:medium => "200x300>", :thumb => "100x150>" },
:storage => :s3,
:s3_credentials => "#{::Rails.root.to_s}/config/s3.yml",
:path => "/photos/:style/:id/:basename.:extension"
# s3.yml
development:
bucket: dev_bucket_name
access_key_id: dev_acc_key
secret_access_key: dev_sec_key
production:
bucket: my_production_bucket
access_key_id: my_access_key_id
secret_access_key: my_secret_key
# environment.rb is empty with regard to uploading.
# uploads_controller.rb
def edit
@candidate = Candidate.find(current_user.user_type_id)
render :layout => 'forms'
end
def update
@candidate = Candidate.find(params[:id])
if @candidate.update_attributes(params[:candidate])
flash[:notice] = "Profile updated successfully."
redirect_to :action => "show", :id => params[:id]
else
flash[:notice] = "There was an error updating your profile."
render :action => "edit", :id => params[:id]
end
end
I don't believe there are any methods involved. I almost hope there is something obviously wrong with my approach because that means it'll get fixed :).
回答1:
For part two this should do it:
@s = "Really Important!*() Document version#123123.newest.pdf"
@s.gsub!(' ','_').downcase! #this will make everything lowercase and replace all spaces with underscores
@s.gsub!(/[^a-zA-Z._]+/,'') #this will remove all numbers and special characters except . and _
puts @s #prints "really_important_document_version.newest.pdf"
Edit: After some more research into paperclip I found the following: http://blog.wyeworks.com/2009/7/13/paperclip-file-rename
Check that link out, I believe it is what you are looking for.
Edit 2: In my initial read of your post I missed the part about pulling out numbers as well, I have modified the regulat expression code to account for that.
来源:https://stackoverflow.com/questions/4419497/amazon-s3-only-accepting-files-with-no-spaces-no-numbers-in-the-title