询问者
WebClient类的UploadFile方法能不能指定字段名啊?!

问题
全部回复
-
你好:
试试这段代码,通过QueryString给服务器传递一个参数:
using (WebClient wc = new WebClient()) { wc.Encoding = Encoding.UTF8; NameValueCollection values = new NameValueCollection(); values.Add("name", "value"); wc.QueryString = values; byte[] ans = wc.UploadFile(address, dumpPath); }
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.- 已编辑 CaillenModerator 2014年3月20日 12:37
-
而用UploadFile方法的时候,是需要指定网页中这个字段的名字的,服务器检查这个名字是否和页面上的字段名相同,如果是才允许上传附件。
这个字段是通过页面中的表单提交给服务器的吧,而且name一般是在页面中自定义的,既然要发送给服务器无非就是get或者post方式,通过QueryString的方式就是get方式。如果你认为这种方式不行的话,那你觉得服务器是如何取得WebClient发送给它的值的呢?服务器又是如何检查“这个名字是否和页面上的字段名相同”的呢?你指的是哪个页面呢?
如果是要指定文件名称的话那请参考MSDN文档:WebClient.UploadFile Method
方法的第二个参数就是文件名称,默认是通过post的方式传递给服务器的。
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.
- 已编辑 CaillenModerator 2014年3月21日 2:00
-
不是的,大家可能不太了解HTTP的Multipart form-data的数据格式。
请大家看看下面Chrome浏览器在提交一个表单的时候的网络监控数据:
这里面有一些是表单的文本字段,其中有一个(红框部分),就是文件上载控件的数据,大家可以看见这个字段是要有一个“name”属性的,HTTP服务器在接收到POST请求之后,会验证这个字段名是否和页面上的字段名一致,如果一致才接受数据,否则将会抛弃这部分数据不保存的。
而我用Fiddler监控C#的UploadFile,得出的结果如下:
很遗憾,貌似UploadFile强制把字段名设置为“file”了!为什么微软的工程师这么独断专横呢?这个名字真的不能修改吗?
现在的问题是,UploadFile方法不能指定这个字段名,于是乎相当于这个方法就是残废了,因为它根本无法上传文件。。。。。除非你的服务器不验证字段名,但是这样的服务器我相信少之又少。。。
da jia hao!
- 已编辑 liubin 2014年3月28日 4:15
-
你有没有尝试一下是否能手动去修改呢?
using (WebClient webClient = new WebClient()) { webClient.Headers.Set("name", "The name you want."); }
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey. -
我好像明白你的意思了,从你的贴图来看name字段属于Content-Disposition部分,不知道直接通过拼接字符串的方式来设置这个header是否有用:
webClient.Headers.Set("Content-Disposition", "form-data;name=\""+myName+"\";filename=18公斤重的猫-1.jpg");
找到一个类似的帖子,可能对你有帮助:
UploadFile with POST values by WebClient
We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
Click HERE to participate the survey.- 已建议为答案 王当文 2015年3月15日 2:54