Use Webclient to Upload File to Web Service
Introduction
This article shall describe an arroyo that may be used to upload whatsoever sort of a file through a web service from a Windows Forms application. The approach demonstrated does not rely on the ASP.Cyberspace file uploader control and allows the developer the opportunity to upload files programmatically and without user intervention. Such an approach may be useful for doing something like processing out the contents of a local message queue when internet service is available (if the user base were mobile and had merely intermittent connectivity). The article besides addresses the use of a file size check as a forerunner to allowing a file to upload through the service.
Figure 1: Test Application Shown Uploading a File.
Figure two: Mixed pocketbook of different file types in transient storage folder.
Getting Started
The solution contains two projects; i is an ASP.Cyberspace Spider web Service project (Uploader) and the other is a Win Forms test awarding (TestUploader) used to demonstrate uploading files through the web method provided in the spider web service project.
The web service project contains only a unmarried web service ( FileUploader ) which in turn contains only a single Spider web Method ( UploadFile ). The Win Forms application contains simply a single form which contains the controls (one textbox and two buttons used in conjunction with an OpenFileDialog control) and code necessary to select and upload files through the web service.
Figure iii: Solution Explorer with the both Projects Visible.
Code: Uploader Web Service Project
The Uploader spider web service project is an ASP.Net web service projection containing a single web service called, "FileUploader"; this web service exposes a single web method called, "UploadFile".
The lawmaking for this web service begins with the following:
- using System;
- using System.Data;
- using System.Web;
- using Arrangement.Collections;
- using System.Web.Services;
- using System.Spider web.Services.Protocols;
- using System.ComponentModel;
- using Arrangement.IO;
- namespace Uploader
- {
- [WebService(Namespace ="http://tempuri.org/" )]
- [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
- [ToolboxItem(false )]
- public class FileUploader : Organisation.Web.Services.WebService
- {
The class starts out with the default imports; I added System.IO to the defaults to back up the use of file and memory streams. The web service namespace is left as the default http://tempuri.org/ which of course volition have to updated if the service were deployed.
The residuum of the code supplied in this class is used to define the web method used to upload the file; the code is annotated. The essential process is that, files converted to byte arrays are passed along with the total name of the file (not the path) including the extension as arguments to the UploadFile web method. The byte array is passed to a retentivity stream, and a file stream is opened pointing to a newly created file (named the name of the original file) inside the target folder used to shop the files. In one case the file stream has been created, the memory stream is written into the file stream then the memory stream and file stream are disposed of.
The web method is setup to return a string; if all goes well, the string returned will read, "OK", if not, the error message encountered will be returned to the caller.
- [WebMethod]
- public string UploadFile( byte [] f, string fileName)
- {
- endeavour
- {
- MemoryStream ms =new MemoryStream(f);
- FileStream fs =new FileStream(System.Web.Hosting.HostingEnvironment.MapPath
- ("~/TransientStorage/" ) +fileName, FileMode.Create);
- ms.WriteTo(fs);
- ms.Close();
- fs.Close();
- fs.Dispose();
- return "OK" ;
- }
- catch (Exception ex)
- {
- return ex.Bulletin.ToString();
- }
- }
Lawmaking: Test Uploader Win Forms Application
The test application contains a unmarried Windows Form class; this form contains a text box used to display the proper noun of the file selected for upload, a scan push button used to launch an open file dialog box which is used to navigate to and select a file for upload, and an upload button which is used to laissez passer the file to web service so that the selected file may be stored on the server.
The lawmaking for this class begins with the post-obit:
- using System;
- using System.Collections.Generic;
- using System.ComponentModel;
- using System.Data;
- using System.Drawing;
- using System.Text;
- using Organization.Windows.Forms;
- using Arrangement.IO;
- namespace TestUploader
- {
- public partial class Form1 : Course
- {
- public Form1()
- {
- InitializeComponent();
- }
- private void Form1_Load( object sender, EventArgs e)
- {
- }
Aside from the default imports, I accept added only System.IO to the list. This being necessary to back up working with files. The namespace and grade declarations are in the default configuration. In addition to Organization.IO, the project also adds in a web reference pointing to the File Uploader spider web service, the reference is given the allonym of Uploader.
The next bit of lawmaking in the class is private method used to prepare the file for submittal to the spider web service and to really brand that submittal. The lawmaking below is annotated to describe the activity merely the essential parts of the functioning are to check the file size to see if the web service will accept the file (by default, the spider web server will have uploads smaller than 4 MB in size, the spider web config file must exist updated in order to back up larger uploads), and to catechumen the file to a byte array. When everything is ready, the byte array and the proper name of the file including the extension is passed to an instance of the web service web method.
Note that, when setting upward the demo, y'all volition have remove and add the spider web reference back into the projection in order for it to work for you lot.
- private void UploadFile( string filename)
- {
- try
- {
- String strFile = System.IO.Path.GetFileName(filename);
- TestUploader.Uploader.FileUploader srv =new
- TestUploader.Uploader.FileUploader();
- FileInfo fInfo =new FileInfo(filename);
- long numBytes = fInfo.Length;
- double dLen = Convert.ToDouble(fInfo.Length / 1000000);
- if (dLen < four)
- {
- FileStream fStream =new FileStream(filename,
- FileMode.Open, FileAccess.Read);
- BinaryReader br =new BinaryReader(fStream);
- byte [] information = br.ReadBytes(( int )numBytes);
- br.Close();
- string sTmp = srv.UploadFile(data, strFile);
- fStream.Close();
- fStream.Dispose();
- MessageBox.Show("File Upload Status: " + sTmp, "File Upload" );
- }
- else
- {
- MessageBox.Bear witness("The file selected exceeds the size limit for uploads." , "File Size" );
- }
- }
- catch (Exception ex)
- {
- MessageBox.Evidence(ex.Message.ToString(),"Upload Error" );
- }
- }
Post-obit the UploadFile method, the next scrap of code is used to handle the browse push's click event. This lawmaking is used merely to display an open file dialog to the user and to take the file selected through that dialog and display the file name in the course's file proper noun text box.
- private void btnBrowse_Click( object sender, EventArgs e)
- {
- openFileDialog1.Title ="Open File" ;
- openFileDialog1.Filter ="All Files|*.*" ;
- openFileDialog1.FileName ="" ;
- try
- {
- openFileDialog1.InitialDirectory ="C:\\Temp" ;
- }
- catch
- {
- }
- openFileDialog1.ShowDialog();
- if (openFileDialog1.FileName == "" )
- render ;
- else
- txtFileName.Text = openFileDialog1.FileName;
- }
The course wraps up with the button click result handler for the Upload button. This handler merely checks for text in the file name text box and, if something is at that place, it sends the value to the Upload method.
- individual void btnUpload_Click( object sender, EventArgs east)
- {
- if (txtFileName.Text != cord .Empty)
- UploadFile(txtFileName.Text);
- else
- MessageBox.Testify("You must select a file first." , "No File Selected" );
- }
That wraps upward all of the client and server side code necessary to upload any sort of file to a server from a Win Forms application.
SummaryThis commodity was intended to demonstrate an easy approach to uploading whatsoever sort of a file to a web server from a Win Forms application. This instance uses the default upload size of 4096 KB, if you demand to upload larger files, you will need to alter this value by changing the httpRuntime maxRequestLength property to the desired value; at the same time you may need to increase the executionTimeout property to a greater value as well in social club to support longer upload times. Take intendance when altering the values as Microsoft has established the default 4 MB limit to provide some rubber against attempts to upload extremely large files that may hamper access to the server.
Source: https://www.c-sharpcorner.com/article/upload-any-type-of-file-through-a-C-Sharp-web-service/
0 Response to "Use Webclient to Upload File to Web Service"
Enregistrer un commentaire