【问题标题】:How to upload a file to website with file contents in post body如何使用帖子正文中的文件内容将文件上传到网站
【发布时间】:2018-08-29 14:26:10
【问题描述】:

如何将文件从浏览器上传到我的网络服务器?服务器是用 Haskell 编写的,使用 Scotty。这是我尝试过的:

服务器:

{-# LANGUAGE OverloadedStrings #-}
module Main where
import qualified Data.ByteString.Lazy as BL
import qualified Web.Scotty as Scot
import qualified Control.Monad.IO.Class as Cm
import qualified Data.Digest.Pure.SHA as Dps

dir :: String
dir = "/home/t/fileUpload/"

main :: IO ()
main =
    Scot.scotty 3000 $ do
        Scot.get "/" $ Scot.file $ dir ++ "index.html"
        Scot.post "/upload" $ do
            contents <- Scot.body
            let fileName = Dps.showDigest $ Dps.sha256 contents
            Cm.liftIO $ BL.writeFile (dir ++ fileName) contents

index.html:

<!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="utf-8">
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input type="file"> <input type="submit" value="Submit"></form>
</body>
</html>

当我在浏览器中访问http://localhost:3000 时,我单击“浏览”按钮,选择一个文件,然后单击“提交”。然后它把我带到一个名为http://localhost:3000/upload 的空白页面,一个文件被保存到“/home/t/fileUpload/somelonghash”。这很好,但问题是保存的文件只包含这样的内容:

-----------------------------172368540915173703481121109126--

这不是原始文件的内容。

【问题讨论】:

    标签: html haskell post scotty


    【解决方案1】:
    -----------------------------172368540915173703481121109126--
    

    这是multipart/form-data 字段边界。如果这就是你得到的全部,这意味着表单不包含任何要发布到服务器的数据。我希望您可以通过给它一个名称来显示您的文件:

    <input type="file" name="myfile">
    

    即使您这样做,您仍然会在响应正文中获得边界和标题,以及您的实际文件内容。您需要做的是解析multipart/form-data 并从那里提取文件内容。如果您使用 files 函数,而不是使用 body,我认为 Scotty 会为您执行此操作。

    【讨论】:

      猜你喜欢
      • 2011-03-27
      • 1970-01-01
      • 2012-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-02-01
      • 2011-10-31
      • 2011-03-02
      • 2010-09-28
      相关资源
      最近更新 更多