首页 新闻 会员 周边

WebClient上传服务器,报(500) 内部服务器错误。

0
悬赏园豆:50 [已解决问题] 解决于 2016-01-21 11:20
  WebClient.UploadFile()方法传到服务器,服务器是MVC控制器接收,一直会报这个错误:WebClient 远程服务器返回错误: (500) 内部服务器错误。
  这是控制器的代码,请问我的代码要怎么改?
 
  public JsonResult Method()
        {
            foreach (string f in Request.Files)
            {
                HttpPostedFileBase file = Request.Files[f];
                string nm = Path.GetFileName(file.FileName);
                file.SaveAs(Server.MapPath(@"d:/" + nm));
            }
            return Json("Success", JsonRequestBehavior.AllowGet);
        }
爛轲的主页 爛轲 | 初学一级 | 园豆:165
提问于:2016-01-20 17:55
< >
分享
最佳答案
0

在这个方法里加个断点,看下是在哪里报错的。

猜测是在 @"d:/" + nm 这里报错的

收获园豆:40
nil | 小虾三级 |园豆:879 | 2016-01-20 18:37

foreach (string f in Request.Files),到这就直接return了

爛轲 | 园豆:165 (初学一级) | 2016-01-21 09:07

@爛轲: 是不是 Request.Files 这里不对 客户端传过来的文件有问题

nil | 园豆:879 (小虾三级) | 2016-01-21 09:31

@nil: 嗯,好了搞好了,顺道问一下上传文件大于4M在哪里配置,客户端还是服务端?

爛轲 | 园豆:165 (初学一级) | 2016-01-21 10:15

@爛轲: IIS大文件上传需要改machine config  可以看下这篇文章 http://www.cnblogs.com/LifelongLearning/archive/2011/12/06/2278247.html

nil | 园豆:879 (小虾三级) | 2016-01-21 10:34
其他回答(2)
0

如果你是要上传文件的话,可以参考以下代码

public ActionResult FileUpLoad()
{
HttpPostedFileBase file = Request.Files["FileUp"];
if (file!=null)
{
string fileName = Path.GetFileName(file.FileName);
string fileExt = Path.GetExtension(fileName);
if (fileExt==".jpg")
{
var list = db.ImageServerInfo.Where(c => c.FlgUsable == true).ToList();
int count = list.Count();
Random r = new Random();
int rNum = r.Next();
int i = rNum % count;
ImageServerInfo model = list[i];
WebClient client = new WebClient();
string address = "http://" + model.ServerUrl + "/FileUp.ashx?serverId=" + model.ServerId + "&ext=" + fileExt;
client.UploadData(address, StreamToByte(file.InputStream));
return Content("文件上传成功");
}
else
{
return Content("文件类型错误");
}
}
else
{
return Content("文件不能为空");
}

}

 

private byte[] StreamToByte(Stream stream)
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
stream.Seek(0, SeekOrigin.Begin);
return buffer;
}

 

 

收获园豆:5
碧绿深蓝 | 园豆:177 (初学一级) | 2016-01-20 19:27

谢谢,不过不需要

支持(0) 反对(0) 爛轲 | 园豆:165 (初学一级) | 2016-01-21 09:08
0

foreach (string f in Request.Files)这句代码改成  foreach (string str in Request.Files.AllKeys)这个试下

收获园豆:5
有时 | 园豆:184 (初学一级) | 2016-01-21 10:13
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册