c#设置uploadFile内容类型
我正在尝试创建一个api调用我的服务器,这将允许我上传.csv文件。
客户端代码
string url = "http://testserver/testapi"; string filePath = @"C:\test.csv"; using (WebClient wc = new WebClient()) { wc.Headers.Add("Content-Type", "text/plain"); byte[] responseArray = wc.UploadFile(url, filePath); }
服务器端代码
string savePath = testSavePath; foreach (string f in Request.Files.AllKeys) { HttpPostedFileBase file = Request.Files[f]; file.SaveAs(savePath); }
我在这行byte[] responseArray = wc.UploadFile(url, filePath);
上遇到exceptionbyte[] responseArray = wc.UploadFile(url, filePath);
奇怪的是,当我看到Request
我看到了
ContentType="multipart/form-data; boundary=---------------------8d006b7c2a5452c"
。
查看UploadFile的文档,我发现当The Content-type header begins with multipart.
时The Content-type header begins with multipart.
将抛出WebException The Content-type header begins with multipart.
我的问题是为什么contentType被设置为multipart,我该如何阻止它这样做?
你的客户端代码好像。 例外可能来自服务器端。 但是你很难判断,因为你没有分享这个例外。 请你做,你会得到更好的答案。
对于multipart内容类型: WebClient.UploadFile
使用Content-Type
标头的值作为文件的内容类型(如果未设置则默认为application/octet-stream
),而不是整个HTTP请求。 实际的HTTP请求总是(如您所见) multipart/form-data
(根据HTTP规范上传文件),您不能(也不应该)更改它。 文档中的注释是指实际文件的内容类型。 这意味着您不能要求WebClient
自行上传多部分文件(将包含在另一个多部分HTTP信封中)。