Ruby on Rails - Encoding::UndefinedConversionError: "\xC3" from ASCII-8BIT to UTF-8

Ruby on Rails - Encoding::UndefinedConversionError: "\xC3" from ASCII-8BIT to UTF-8

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

那是用Net::FTP'sgettextfile的方法。 这是我的代码:

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

如果我注释掉 ftp.gettextfile 行,错误就会不断出现。

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

对于从 google 来到这里的任何人,这就是我修复编码错误的方法。

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

.force_encoding("UTF-8")

所以在您将文件声明为这样的变量之前:

csv_file = params[:file].read.force_encoding("UTF-8")

希望这对一些人有所帮助,因为我长期以来一直遇到这个问题,但现在它成功了!