优化用户头像逻辑

This commit is contained in:
nwb 2014-08-29 15:28:32 +08:00
parent 51b21000a7
commit c8e895ec74
2 changed files with 55 additions and 1 deletions

View File

@ -28,6 +28,13 @@ class AvatarController < ApplicationController
if @temp_file && (@temp_file.size > 0)
diskfile=disk_filename(@source_type,@source_id)
@urlfile='/' << File.join("images","avatars",avatar_directory(@source_type),avatar_filename(@source_id,@image_file))
# 用户头像上传时进行特别处理
if @source_type == 'User'
diskfile += "temp"
@urlfile += "temp"
end
logger.info("Saving avatar '#{diskfile}' (#{@temp_file.size} bytes)")
path = File.dirname(diskfile)
unless File.directory?(path)
@ -96,7 +103,16 @@ class AvatarController < ApplicationController
unless diskfile.nil? || diskfile == ""
path = File.dirname(diskfile)
if File.directory?(path) && File.exist?(diskfile)
File.delete(diskfile)
# 用户头像进行特别处理
if @source_type == 'User'
diskfile1 = diskfile + 'temp'
File.open(diskfile1, "wb") do |f|
buffer = "DELETE"
f.write(buffer)
end
else
File.delete(diskfile)
end
end
end
rescue e do

View File

@ -76,6 +76,8 @@ class MyController < ApplicationController
def account
@user = User.current
@pref = @user.pref
diskfile = disk_filename('User', @user.id)
diskfile1 = diskfile + 'temp'
if request.post?
@user.safe_attributes = params[:user]
@user.pref.attributes = params[:pref]
@ -97,6 +99,33 @@ class MyController < ApplicationController
@se.student_id = params[:no] if params[:no]
if @user.save && @se.save
# 头像保存
if File.exist?(diskfile1)
if File.exist?(diskfile)
File.delete(diskfile)
end
File.open(diskfile1, "rb") do |f|
buffer = f.read(10)
if buffer != "DELETE"
File.open(diskfile1, "rb") do |f1|
File.open(diskfile, "wb") do |f|
buffer = ""
while (buffer = f1.read(8192))
f.write(buffer)
end
end
end
# File.rename(diskfile + 'temp',diskfile);
end
end
end
# 确保文件被删除
if File.exist?(diskfile1)
File.delete(diskfile1)
end
@user.pref.save
@user.notified_project_ids = (@user.mail_notification == 'selected' ? params[:notified_project_ids] : [])
set_language_if_valid @user.language
@ -104,8 +133,17 @@ class MyController < ApplicationController
redirect_to user_path(@user)
return
else
# 确保文件被删除
if File.exist?(diskfile1)
File.delete(diskfile1)
end
@user
end
else
# 确保文件被删除
if File.exist?(diskfile1)
File.delete(diskfile1)
end
end
end