Ruby on Rails - 编码:: UndefinedConversionError:"\ xC3"从ASCII-8BIT到UTF-8

Dve*_*vex 8 ruby ftp encoding ruby-on-rails utf-8

我有一个通过FTP从大型机中获取平面文件的进程.这通常适用于某些文件.在其他人中,我得到:Encoding::UndefinedConversionError: "\xC3" from ASCII-8BIT to UTF-8

这是使用Net::FTP's gettextfile方法.这是我的代码:

def find_file( position, value ) # => Value = CLKDRP03.txt, Forget the variable Position

    ftp = Net::FTP.new('IP') # => status 200
    ftp.login('user','pass') # => True

    files = ftp.list('*' + value + '*') # => Obtain the file

    if files[0] != nil

      str_file = files[0].split(" ").last # => Obtain the name of the file. In this case CLKDRP03.txt

      ftp.gettextfile(str_file,'data/input/' + str_file) # => ERROR!, str_file = CLKDRP03.txt
      # => data/input is the path where I put the files from FTP.
      return str_file

    else  
      return false
    end

end
Run Code Online (Sandbox Code Playgroud)

如果我评论该行ftp.gettextfile,则错误不断出现.

提前致谢!对不起我的英语不好.

Cyr*_*Zei 16

对于从谷歌来这里的任何人来说,这就是我修复编码错误的方法.

在您声明打开文件之前添加此代码

.force_encoding("UTF-8")
Run Code Online (Sandbox Code Playgroud)

所以在将文件声明为如下变量之前:

csv_file = params[:file].read.force_encoding("UTF-8")
Run Code Online (Sandbox Code Playgroud)

希望这会帮助一些人,因为我有这个问题很长一段时间,但现在它工作正常!

  • 知道这一点也很有用,可以使用“Encoding.default_external”检查外部事物的默认编码,并将其设置为 UTF-8(如果这是您主要处理的内容)“Encoding.default_external = Encoding::UTF_8”。我也遇到了类似的问题,但是宝石中有一些东西,所以我不能太容易地强制编码。 (2认同)