MVC and webservice upload files (images and videos), and hope to help some friends, mvcwebservice
I recently worked on a project to upload images and videos to the server (separated from the image server). I have been searching for images online for a long time and have not found any complete information.
It took me a long time to complete the code. Many of my friends may have implemented it. I don't want to share the code. I don't want to laugh !!
Paste the following code: MVC code first:
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; // create a file stream object 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 ;}
Second: webservice code:
[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 ("/", ""); // define and instantiate a memory stream to store the submitted byte array // MemoryStream m = new MemoryStream (fs ); /// define the actual object, Save the uploaded file. FileStream f = new FileStream (requestPath + newName + expendName, FileMode. create); // write data in the internal memory to the physical file m. writeTo (f); m. close (); f. close (); f = null; m = null; return requestPath + newName + expendName;} catch (Exception error) {} return "";}
Return the URL of the uploaded file to save it to the database (change it as needed)
Html code
<Form id = "form1" action = "/VideoAdmin/UploadVide" method = "post" enctype = "multipart/form-data"> <table cellspacing = "0" cellpadding =" 0 "border =" 0 "class =" tableadd "> <tr> <td> select video: </td> <input id = "btnfile" type = "file" name = "file"> <input id = "txturl" type = "text" name =" txturl "value =" D: "/> <input id =" uploatvoide "type =" submit "value =" Upload video "/> </td> </tr> <td> video name </td> <input id = "testvideoname" type = "text" readonly = "readonly" value = "dddsds"/> </td> </tr> </ table> </form>
The Code has been tested and can be used. I hope it can help you, but it is not easy to write. I hope you don't laugh at it!