【问题标题】:Http POST request with multipart/form-data using clj-ajax使用 clj-ajax 的多部分/表单数据的 Http POST 请求
【发布时间】:2017-05-08 22:01:42
【问题描述】:

我有一个端点,我可以像这样使用 curl 上传文本文件:

curl -X POST -H "Content-Type: multipart/form-data" -F "file=@/resources/speciesDiffusion.tree" http://localhost:4000/continuous/tree 

现在我需要从浏览器发送一个类似的请求,但是

 (ajax/ajax-request
  {:uri (str "http://localhost:4000" "/continuous/tree")
   :method :post
   :params {:treefile file}
   :handler #(println %1)
   :format (ajax/text-request-format)
   :response-format (ajax/json-response-format {:keywords? true})})

给了我一个(很好的 json 转换,所以我得到了那部分,这很好)错误响应:

[false {:status 500, :status-text , :failure :error, :response {:timestamp 1494279686227, :status 500, :error Internal Server Error, :exception org.springframework.web.multipart.MultipartException, :message Current request is not a multipart request, :path /continuous/tree}}]

另外,在浏览器中,我可以看到内容类型标头未正确设置,但我无法使其与 :format 和 :params 的任何其他组合一起使用。

【问题讨论】:

    标签: ajax clojure clojurescript


    【解决方案1】:

    cljs-ajax 项目的 README 中有一些示例。例如:

    (let [form-data (doto
                        (js/FormData.)
                      (.append "id" "10")
                      (.append "file" js-file-value "filename.txt"))]
      (POST "/send-file" {:body form-data
                          :response-format (raw-response-format)
                          :timeout 100}))
    

    https://github.com/JulianBirch/cljs-ajax

    【讨论】:

    • 谢谢,但是我很清楚现有的文档,很遗憾没有解决问题。
    • 我建议再读一次,因为您的示例没有指定 :body 或任何 :headers
    • 根据官方文档: :params - 将与请求一起发送的参数,取决于格式: :transit 和 :edn 可以发送任何内容, :json 和 :raw 需要给一个映射。 GET 会将参数添加到查询字符串中,POST 会将参数放在正文中。
    • 好的。但正如我已经演示过的以及文档所暗示的那样,对于多部分 POST 而言,情况并非如此。
    • 问题实际上有点不同 - 我发送的是文件内容(通过 js/FileReaders onLoad 事件读取),而不是简单的 js 文件。
    【解决方案2】:

    根据我的评论,问题不在于请求,而在于调度它的 f-tion,即我正在读取文件内容而不是像这里发送原始对象:

    (defn handle-file-upload [evt]
      (let [target (.-currentTarget evt)
            js-file (-> target .-files (aget 0))]
        (do
          (re-frame/dispatch [:post-file {:file js-file
                                                     :name (.-name js-file)}])
          (set! (.-value target) ""))))
    
    (defn upload-button []
      (fn []
    [:input {:class "none"
                 :id "file-upload"
                 :type "file"
                 :on-change #(handle-file-upload %)}]))
    

    在哪里

    :后置文件

    是一个事件,它调用执行 POST 请求的处理程序。

    【讨论】:

      猜你喜欢
      • 2012-11-27
      • 2017-10-05
      • 1970-01-01
      • 2014-06-01
      • 1970-01-01
      • 2017-10-27
      • 2013-07-20
      • 1970-01-01
      相关资源
      最近更新 更多