1. 程式人生 > >web檔案上傳,webapi後臺接收

web檔案上傳,webapi後臺接收

後臺:

        public string Post()
        {
            string key = HttpContext.Current.Request["key"];
            string value = HttpContext.Current.Request["value"];
            HttpFileCollection files = HttpContext.Current.Request.Files;

            foreach (string f in files.AllKeys)
            {
                HttpPostedFile file = files[f];
                if (string.IsNullOrEmpty(file.FileName) == false)
                    file.SaveAs(HttpContext.Current.Server.MapPath("~/App_Data/") + file.FileName);
            }

            return key + value;
        }

前端:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
</head>
<body>
    <form name="form" action="http://localhost:31855/api/values" method="post" enctype="multipart/form-data">
        <input type="text" name="key" id="txtKey" />
        <br />
        <input type="text" name="value" id="txtValue" />
        <br />
        <input type="file" name="file" id="upFile" />
        <input type="file" name="file2" id="File1" />
        <br />
        <input type="submit" id="btnSubmit" value="Submit" />
    </form>
</body>
</html>