2

I want to let admins import contacts via csv files into the database. Therefore I am using the ruby csv library and the following code snippet:

 if request.post? && params[:file].present?
     inputFile = params[:file].read
     CSV.foreach(inputFile) do |row|
         #save row here
     end
 end

However in CSV.foreach(inputFile) do |row| I get an "Errno::ENAMETOOLONG - File name too long"-error and the error message shows me that it uses the whole csv file as file name.

Does anyone know why it does that?

BTW: The csv file is using ',' and '/n' as delimiters.

3 Answers 3

11

Thanks to the input of the other answers I found the solution myself. The problem is that .read turns the file into a string with the contents, but CSV.foreach() expects a filename or path . Using .path instead solves the problem:

 if request.post? && params[:file].present?
     inputPath = params[:file].path
     CSV.foreach(inputPath) do |row|
         #save row here
     end
 end
Sign up to request clarification or add additional context in comments.

Comments

1

It could have to do with the .read call on line 2. Somehow inputFile is turning into the contents of the csv and not the name of the file itself. That would lead me to believe there is a problem with you setting the inputFile variable. My guess is that .read is not working in the way you intended it to.

Comments

0

Try to just remove the .read when you are getting the value from params. Then the variable inputFile may have the path of file to pass to CSV.foreach

1 Comment

Just removing the .read results in this error: "no implicit conversion of ActionDispatch::Http::UploadedFile into String". But if I add .path everything finally works :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.