0

I have incorporated an import feature in my app. While developing it, I have given the path where it checks for a particular file while importing. But I don't understand how will that work when deployed on the web. Every user will have a different file that they should be able to upload. What path will it consider then? Consider the following code:

 #This is the view file from where i upload the CSV.
    <h4>Import/Export (from/to CSV format)</h4>
    <input type="file" name="csv" />
    <br />
    <input type="submit" name="import" value="Import from CSV"/>
          <br />
    <input type="submit" name="export" value="Export questions to CSV" >

The following is the controller that handles it:

 def import

questionnaire_id = (params[:id])
begin
    file_data = File.read(Rails.root.join('spec/features/import_export_csv_oss/'+params[:csv]))
    a = QuestionnaireHelper.get_questions_from_csv(file_data,params[:id])
    redirect_to edit_questionnaire_path(questionnaire_id.to_sym), notice: "All questions have been successfully imported!"
   rescue
  redirect_to edit_questionnaire_path(questionnaire_id.to_sym), notice: $ERROR_INFO
end

So, currently, it checks in the import_export_csv_oss folder for the file that I want to upload. In my development environment, I can put that file there. But when it's deployed on the web, will it work when a user tries to upload a file from his local machine?

4

1 回答 1

0

如果您不打算将文件保存在服务器上而只导入数据,则应以本地文件路径作为参数发送数据,并将标头“Content-Type”设置为“multipart/form-data”

def import
      data = CSV.read(filepath.tempfile, { encoding: "UTF-8", headers: true, header_converters: :symbol, converters: :all })
      #code to process and save it
end

这将创建一个仅对请求有效的 ruby​​ 临时文件(除非您将其保存在指定位置),您可以在内存中读取该文件。在此处阅读有关临时文件的更多信息 https://edgeapi.rubyonrails.org/classes/ActionDispatch/Http/UploadedFile.html

这是使用 curl 的示例请求

curl -H "Content-Type: multipart/form-data" -H "token: Xh7uHRUsnjVaaMd12" -X POST -F "parameter_1=5b71b02" -F "filepath=@/Users/mojo/Downloads/dyp.csv;type=text/csv" https://website/url
于 2019-09-05T10:29:10.413 回答