WebService upload download file

xiaoxiao2021-03-06  52

With the development of Internet technology and the increasing cross-platform demand, Web Services is getting wider and wider, but we need to deliver string information through Web Services, but also need to pass binary information. Below, we will show how to download files from the server from the server from the server to the client from the server to the server from the server.

One: Display and download files via Web Services

The name of the web services established here is GetBinaryFile, providing two public methods: getImage () and getImageType (), the former returns the binary byte array, the latter returns the file type, where the getImage () method has a parameter Used to select the file name to display or download at the client. The file we have displayed and downloaded can not be in the virtual directory, the benefits of using this method are: can display and download control according to the permissions, from the following method. We can see that the actual file location is not in the virtual directory. Under, the file can be better permissible to the file, which is particularly useful in the case of high security. This feature can be implemented in a STREAM object in the previous ASP program. In order to facilitate the reader to test, all source code is listed here, and the introduction and comment in the source code.

First, establish a getBinaryFile.asmx file:

We can create a new C # ASPXWEBCS project in vs.net, then "Add new item", select "Web Service", and set the file name as: getBinaryFile.asmx, enter the following code in View Code, ie: GetBinaryFile.asmx.cs:

using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Web; using System.Web.UI; using System.Web.Services; using System.IO;

Namespace Xml.sz.luohuedu.net.aspxwebcs {///

/// getBinaryFile's summary description. /// Web Services Name: getBinaryFile /// Function: Returns the binary byte array of file objects on the server. /// [WebService (Namespace = "http://xml.sz.luohuedu.net/"; ") In Web Services, using the .NET framework to deliver binary files.")] Public Class GetBinaryFile : System.web.services.Webservice {

#Region Component Designer Generated Code // Web Service Designer The private icontainer components = NULL;

///

/// Clean all the resources being used. /// Protected Override Void Dispose (Bool Disposing) {IF (Disposing && Components! = NULL) {Components.dispose ();} Base.dispose (Disposing);

#ndregion

Public class images: system.web.services.Webservice {///

/// web service provides the method of returning the byte array of a given file. /// [WebMethod (Description = "web service provides the byte array of a given file")] public Byte [] getImage (String RequestFileName) {// get a picture of the server //// / If you test it yourself, pay attention to modify the following actual physical path if (RequestFileName == ") Return getBinaryFile (" D: Picture.jpg "); Elsereturn GetBinaryFile (" D: " RequestFileName); } /// /// getBinaryFile: Returns the byte array of the file path. /// /// /// public byte [] getBinaryFile (String filename) {if (file.exists (filename) ) {Try {/// Open existing files for reading. FileStream S = file.openread (filename); Return ConvertStreamTobyteBuffer (s);} catCH (Exception E) {Return New Byte [0];}} else {return new byte [0];}} /// / // ConvertStreamTobyteBuffer: Converts a given file stream to a binary byte array. /// /// /// public byte [] convertStreamTroBytebuffer (system.io.stream theestream) {Int B1; System .Io.MemoryStream TempStream = new system.io.MemoryStream (); while ((b1 = thisstream.readByte ())! = - 1) {TempStream.writebyTe ((byte) b1));} return tempstream.toarray ( } [WebMethod (Description = "web service provides a given file type.")] Public string getimageType () {// This is just a test, you can perform dynamic output Return "image according to the actual file type / jpg ";}}}}

Once we have created the above ASMX file, we can write this web services after compiling.

Let's first "add Web reference", type: http://localhost/aspxwebcs/getbinaryfile.asmx. Below, we write the intermediate file displaying the file: getBinaryFileSpo.aspx, here, we only need to write code in the postcode, getBinaryFileShow.aspx.cs file content is as follows: use system; using system.collections; using system.componentmodel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; using System. Web.services;

Namespace aspxwebcs {///

/// getBinaryFileSHOW summary description. /// public class getBinaryFileShow: system.Web.ui.page {

Private void page_load (Object sender, system.eventargs e) {// Place the user code here to initialize the page // definition and initialize the file object; XML.SZ.LuoHuedu.Net.aspxwebcs.getBinaryFile.Images Oimage; Oimage = New xml.sz.luohuedu.net.aspxwebcs.getBinaryFile.Images (); // gets a binary file byte array; byte [] image = oimage.getiMage ("); //) To support storage area for memory Stream system.io.MemoryStream MemStream = new system.io.MemoryStream (image); // definition and instantiate Bitmap object Bitmap BM = new bitmap (memstream); // // / / According to different conditions; Response .Clear (); //// If the request string specifies the download, download the file; // Otherwise, it is displayed in the browser. if (Request.QueryString ["Download"] == "1") {response.buffer = true; response.contenttype = "Application / OCTET-stream"; //////////////////////////////bit. You can actually decide according to the situation. Response.addheader ("Content-Disposition", "Attachment; FileName = OK.jpg");} elseresponse.contentType = Oimage.GetImageType (); response.binarywrite (image); response.end (); r

#Region Web Form Designer Generated CodeOverride Protected Void OnNit (Eventargs E) {//// Codegen: This call is required for the ASP.NET Web Form Designer. //Initializecomponent();Base.oninit (E);

///

/// Designer supports the required method - do not use the code editor to modify the // / this method. /// private () {this.load = new system.eventhandler (this.page_load);} # endregion}}

Finally, we write the final browsing page: getBinaryFile.aspx, this file is simple, only the aspx file is required, the content is as follows:

<% @ Page language = "c #" codebehind = "getBinaryFile.aspx.cs" autoeventwireup = "false" inherits = "aspxwebcs.getbinaryfile"%> Display and download file </ title> <meta name =" generator "content =" text = "code_language" content = "c # "> <meta name =" vs_defaultClientScript "content =" javascript "> <meta name =" vs_targetSchema "content =" http://schemas.microsoft.com/intellisense/ie5 ";> </ HEAD> <body MS_POSITIONING =" GridLayout "> <form id =" getBinaryFile "method =" post "runat =" server "> <font face =" Song body "> <ask: hyperlink id =" hyperlink1 "navigateurl =" getBinaryFileShow.aspx? Download = 1 "Runat = "Server"> Download File </ asp: hyperlink> <! - below is Download Document directly -> <ask: image id = "image1" imageURL = "getBinaryFileShow.aspx" runat = "server" > </ asp: image> </ font> </ form> </ body> </ html></p> <p>2: Upload files through Web Services</p> <p>There are many ways to upload files to the server. In the method of loading files with Web Services, the following methods should be the easiest. We are still like the previous example, first build upload.asmx files, which is as follows, which has been done in the following:</p> <p>Using system.collections; using system.componentmodel; using system.data; using system.web; using system.Web.Services; use system.io;</p> <p>Namespace Xml.sz.luohuedu.net.aspxwebcs {/// <Summary> /// Upload Summary Description. /// </ summary> [WebService (namespace = "http://xml.sz.luohuedu.net/"; ") In Web Services, in Web Services,")] Public Class Upload: System.Web.Services.Webservice {public upload () {// codegen: This call is the initializationComponent () () necessary for the ASP.NET Web service designer.</p> <p>#Region Component Designer Generated Code</p> <p>// Web Service Designer The private icontainer components = null;</p> <p>/// <summary> /// Designer supports the required method - do not use the code editor to modify the // / this method. /// </ summary> private void initializecomponent ()}</p> <p>/// <Summary> /// Clean all the resources being used. /// </ summary> Protected Override Void Dispose (Bool Disposing) {IF (Disposing && Components! = NULL) {Components.dispose ();} Base.dispose (Disposing);</p> <p>#ndregion</p> <p>[WebMethod (Description = "web service providing method, return whether the file upload is successful or not.")] Public string UploadFile (Byte [] fs, string filename) {try {// definition and instantiate a memory flow, Store the array of bytes submitted. MemoryStream M = New MemoryStream (fs); // Defines the actual file object to save the uploaded file. FILESTREAM F = New FileStream (Server.Mappath (") " FileName, FileMode.create); // Writing the data in the inner memory M.Writto (f); m.close () f.close (); f = null; m = null; return "file has been uploaded successfully.";} catch (eXception ex) {return ex. subssage;}}}}}</p> <p>To upload files, you must provide a form to provide the user's selection. Let's establish such a page UPLoad.aspx to provide file upload:</p> <p><% @ Page language = "c #" codebehind = "UPLOAD.ASPX.CS" autoeventwireup = "false" inherits = "aspxwebcs.upload"%> <! Doctype html public "- // w3c // DTD HTML 4.0 Transitional // En "> <html> <head> <title> Upload file </ title> <meta name =" generator "Content =" Microsoft Visual Studio .Net 7.0> <meta name = "Visual" Content = "code_language Basic 7.0 "> <meta name =" vs_defaultClientScript "content =" javascript "> <meta name =" vs_targetSchema "content =" http://schemas.microsoft.com/intellisense/ie5 ";> </ HEAD> <body MS_POSITIONING = "GridLayout"> <form id = "form1" method = "post" runat = "server" encty = "multipart / form-data"> <input id = "myfile" type = "file" runat = "server"> <br> <ASP: Button ID = "Button1" runat = "server" text = "Upload File"> </ asp: button> </ form> </ body> </ html> We want to process It is in the post-sample code, the following detailed introduction, Upload.aspx.cs:</p> <p>using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls Using system.web.ui.htmlcontrols; using system.web.services; using system.io;</p> <p>Namespace aspxwebcs {/// <summary> /// Upload's summary description. /// Web Services by using this method to upload file /// </ summary> public class Upload: System.Web.UI.Page {protected System.Web.UI.HtmlControls.HtmlInputFile MyFile; protected System.Web.UI.WebControls .Button button1;</p> <p>Private Void Page_Load (Object Sender, System.EventArgs E) {// Place the user code here to initialize the page} #Region Web form Designer generated codeoverride protected void oninit (Eventargs E) {//// codegen: This call is ASP The .NET Web Form Designer is required. //Initializecomponent();Base.oninit (E);</p> <p>/// <summary> /// Designer supports the required method - do not use the code editor to modify the // / this method. /// </ summary> private () {this.button1.click = new system.eventhandler (this.button1_click); this.load = new system.eventhandler (this.page_load);</p> <p>} #endregion</p> <p>private void Button1_Click (object sender, System.EventArgs e) {/// was first uploaded file information and file stream if (MyFile.PostedFile = null!) {System.Web.HttpFileCollection oFiles; oFiles = System.Web.HttpContext.Current .Request.files; if (Ofiles.count <1) {response.write ("Please select a file."); Response.end ();</p> <p>String filepath = ofiles [0] .filename; if (filepath == "|| filepath == null) {response.write (" Please select a file. "); response.end ();} String filename = filepath. Substring (FilePath.lastIndexOf (") 1); Try {/// Handling uploaded file stream information. Byte [] b = new byte [ofiles [0] .contentLength]; system.io.stream fs; xml.sz.luhuedu.net.aspxwebcs.upload o; o = new xml.sz.luohuedu.net.aspxwebcs.upload (); fs = (system.io.stream) Ofiles [0] .inputstream; fs.read (b, 0, 0i [0] .contentLength); // / / Call Web Services UPLoadFile method to upload files. Response.write (O. UploadFile (B, FileName)); fs.close ();} catch (exception ex) {response.write (ex. subssage);}} else {response.write ("Please select File") }}}}}</p> <p>Finally, you need to pay attention to: When saving files, you should make sure that the full path to the specified file (for example, "c: //myfiles/Picture.jpg) and make sure the account to be stored for ASP.NET The write permission of the directory. When uploading a large file, you can use the maxRequestLength attribute of the element to increase the maximum allowable value of the file size, for example:</p> <p><configuration> <system.Web> <httpruntime maxRequestLength = "1048576" ExecutionTIMEOUT = "3600" /> </ system.web> </ configuration> where: maxRequestLength: The maximum number of bytes that indicate the HTTP mode supported by ASP.NET . This limitation can be used to prevent denial of service attacks caused by users from passing a large number of files to the server. The specified size is in KB. The default is 4096 KB (4 MB). ExecutionTIMEOUT: The maximum number of seconds allowing the request is allowed before being automatically turned off by ASP.NET. In the case where the file is exceeded, if the DNS error is generated or the service is not available, please modify the above configuration, increase the configuration number.</p> <p>In addition, when uploading large files, you may also receive the following error message:</p> <p>ASPNET_WP.EXE (PID: 1520) is reclaimed because the memory consumption exceeds 460 MB (can be used by 60% of RAM).</p> <p>If you encounter this error message, add the value of the MemoryLimit property in the element of the web.config file of the application. E.g:</p> <p><Configuration> <system.web> <processmodel memorylimit = "80" /> </ system.web> </ configuration></p> <p>I test on my own machine, you can upload 50m or more files. The above code is passed under Windows XP .NET 1.0 vs.net2002. Reprinted: Mengxian</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-116206.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="116206" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.041</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'SbWxDQmMEhfyoVTXDHhARFjmthT_2BQMcqcjGtr6YjDQv20KO3Nnggm5xXtM4MmgPTyZXrX91vbYSXbz7YxtkY8Q_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>