asp.net webapi2.0文件上传

        [Route("api/uploadFile")]
        public ReturnMessage PostFile(string saveDirName)
        {
            HttpRequest httpRequest = HttpContext.Current.Request;
            string rootPath = HttpContext.Current.Server.MapPath("~/");
            string saveRootPath = Path.Combine(rootPath, "fileDB");//上传文件的根目录

            string realSavePath = Path.Combine(saveRootPath, saveDirName);//要放文件的子目录

            ReturnMessage returnMessage = new ReturnMessage();

            string v = httpRequest.ServerVariables["REMOTE_ADDR"];
            try
            {
                if (!Directory.Exists(realSavePath))
                    Directory.CreateDirectory(realSavePath);

                if (httpRequest.Files.Count > 0)
                {
                    var docfiles = new List<string>();
                    foreach (string file in httpRequest.Files)
                    {
                        var postedFile = httpRequest.Files[file];//上传过来的文件
                        string savePath = Path.Combine(realSavePath, postedFile.FileName);
                        postedFile.SaveAs(savePath);
                        docfiles.Add(savePath);
                    }
                    returnMessage.Code = "success";
                }
                else
                {
                    returnMessage.Code = "failure";
                    returnMessage.Data = "没有文件";

                }
            }
            catch (Exception ex)
            {
                returnMessage.Code = "failure";
                returnMessage.Data = ex.Message;
            }
            return returnMessage;


        }
posted @ 2023-03-30 15:54  沈先生爱猫咪  阅读(167)  评论(0编辑  收藏  举报