最近做一个项目,要把图片和视频传到服务器上(网站与图片服务器分开),在网上找了好久,没找到完整的资料。
自己也折腾了半天,才把完整的代码实现完。可能好多朋友都有实现过,没分享代码吧,写得不好希望不要见笑!!
下面贴代码吧:首先MVC代码:
public string UploadVide() { string requesturl = ""; string result = "video/Videoitem/"; HttpFileCollectionBase fileToUpload = Request.Files; foreach (string file in fileToUpload) { var curFile = Request.Files[file]; Stream sr= curFile.InputStream; byte[] filebyt = new byte[curFile.ContentLength]; Stream fileStream = curFile.InputStream;//建立文件流对象 fileStream.Read(filebyt, 0, curFile.ContentLength); ServiceReference1.WebMp4serviceSoapClient sf = new ServiceReference1.WebMp4serviceSoapClient(); requesturl= sf.UpLoadStream(filebyt, curFile.FileName, "D:\\Video\\"); } // ServiceReference1.WebMp4serviceSoapClient sf = new ServiceReference1.WebMp4serviceSoapClient(); //sf.u return requesturl; }其次:webservice代码:
[WebMethod] public string UpLoadStream(byte[] fs, string fileName, string requestPath) { try { string oldName = System.IO.Path.GetFileName(fileName); string expendName = System.IO.Path.GetExtension(oldName); string newName = DateTime.Now.ToString().Replace(" ", "").Replace(":", "").Replace("-", "").Replace("/", ""); ///定义并实例化一个内存流,以存放提交上来的字节数组 /// MemoryStream m = new MemoryStream(fs); ///定义实际文件对象,保存上载的文件。 FileStream f = new FileStream(requestPath + newName + expendName, FileMode.Create); ///把内内存里的数据写入物理文件 m.WriteTo(f); m.Close(); f.Close(); f = null; m = null; return requestPath + newName + expendName; } catch (Exception error) { } return ""; }返回上传文件URL用于保存到数据库(根据你自己的需求来改)
html代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 < form id="form1" action="/VideoAdmin/UploadVide" method="post" enctype="multipart/form-data"> < table cellspacing="0" cellpadding="0" border="0" class="tableadd"> < tr > < td > 选择视频: </ td > < td > < input id="btnfile" type="file" name="file">< input id="txturl" type="text" name="txturl" value="D:" />< input id="uploatvoide" type="submit" value="上传视频" /> </ td > </ tr > < tr > < td > 视频名称 </ td > < td > < input id="testvideoname" type="text" readonly="readonly" value="dddsds" /> </ td > </ tr > </ table > </ form >
代码经过测试,是可以的,希望帮到大家,写得不好,还希望不要见笑!