中级二 上传图片

web api 上传文件,可以这样做

   public async Task<HttpResponseMessage> PostFormData()
        {
            // Check if the request contains multipart/form-data.  
            // 检查该请求是否含有multipart/form-data  
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }
 
            string root = HttpContext.Current.Server.MapPath("~/App_Data");
            var provider = new MultipartFormDataStreamProvider(root);
 
            try
            {
                // Read the form data.  
                // 读取表单数据  
                await Request.Content.ReadAsMultipartAsync(provider);
 
                // 显示所有“键-值”对  
                foreach (var key in provider.FormData.AllKeys)
                {
                    foreach (var val in provider.FormData.GetValues(key))
                    {
                        //Trace.WriteLine(string.Format("{0}: {1}", key, val));
                    }
                }
                // This illustrates how to get the file names.  
                // 以下描述如何获取文件名  
                foreach (MultipartFileData file in provider.FileData)
                {
                    Trace.WriteLine(file.Headers.ContentDisposition.FileName);
                    Trace.WriteLine("Server file path: " + file.LocalFileName);
                }
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            catch (System.Exception e)
            {
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
            }
        }

pc 上传文件可以这样做

public IHttpActionResult getTest2()
{

string id=HttpContext.Current.Request["id"];
string name = HttpContext.Current.Request["name"];
HttpFileCollection files = HttpContext.Current.Request.Files;

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

return Ok("success2");
}

猜你喜欢

转载自www.cnblogs.com/haigui-zx/p/9965332.html