file upload c# .net core 2 table

Introduction

This article shall describe an arroyo that may be used to upload whatever sort of a file through a web service from a Windows Forms awarding. The approach demonstrated does non rely on the ASP.Internet file uploader control and allows the programmer the opportunity to upload files programmatically and without user intervention. Such an approach may exist 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 only intermittent connectivity). The commodity too addresses the apply of a file size check equally a forerunner to allowing a file to upload through the service.

img1.jpg

Figure ane: Test Application Shown Uploading a File.

img2.jpg

Figure 2: Mixed bag of different file types in transient storage folder.

Getting Started

The solution contains two projects; 1 is an ASP.Internet 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 web service project.

The spider web service project contains simply a single spider web service ( FileUploader ) which in turn contains only a single Web Method ( UploadFile ). The Win Forms application contains only a single form which contains the controls (one textbox and 2 buttons used in conjunction with an OpenFileDialog control) and code necessary to select and upload files through the web service.

img3.jpg

Figure three: Solution Explorer with the both Projects Visible.


Code:  Uploader Web Service Projection

The Uploader web service project is an ASP.NET web service projection containing a single web service called, "FileUploader"; this spider web service exposes a single web method called, "UploadFile".

The code for this web service begins with the following:

  1. using  Organisation;
  2. using  System.Data;
  3. using  Organization.Web;
  4. using  Organization.Collections;
  5. using  System.Spider web.Services;
  6. using  System.Web.Services.Protocols;
  7. using  Organisation.ComponentModel;
  8. using  System.IO;
  9. namespace  Uploader
  10. {
  11.     [WebService(Namespace ="http://tempuri.org/" )]
  12.     [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  13.     [ToolboxItem(faux )]
  14. public grade  FileUploader : Organization.Web.Services.WebService
  15.     {

The class starts out with the default imports; I added System.IO to the defaults to support the use of file and memory streams. The web service namespace is left as the default http://tempuri.org/ which of course will accept to updated if the service were deployed.

The remainder of the code supplied in this grade is used to define the web method used to upload the file; the lawmaking is annotated. The essential process is that, files converted to byte arrays are passed along with the full 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 proper noun of the original file) within the target folder used to store the files. In one case the file stream has been created, the retentiveness stream is written into the file stream and and then the memory stream and file stream are disposed of.

The spider 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.

  1. [WebMethod]
  2. public string  UploadFile( byte [] f, cord  fileName)
  3. {
  4. endeavour
  5.     {
  6.         MemoryStream ms =new  MemoryStream(f);
  7.         FileStream fs =new  FileStream(Arrangement.Web.Hosting.HostingEnvironment.MapPath
  8.                     ("~/TransientStorage/" ) +fileName, FileMode.Create);
  9.         ms.WriteTo(fs);
  10.         ms.Close();
  11.         fs.Close();
  12.         fs.Dispose();
  13. return "OK" ;
  14.     }
  15. catch  (Exception ex)
  16.     {
  17. return  ex.Message.ToString();
  18.     }
  19. }

Code:  Test Uploader Win Forms Application

The test application contains a single Windows Form grade; this form contains a text box used to display the name of the file selected for upload, a scan button used to launch an open file dialog box which is used to navigate to and select a file for upload, and an upload push button which is used to pass the file to spider web service and so that the selected file may be stored on the server.

The code for this form begins with the following:

  1. using  System;
  2. using  System.Collections.Generic;
  3. using  Organization.ComponentModel;
  4. using  Arrangement.Information;
  5. using  Arrangement.Cartoon;
  6. using  Organisation.Text;
  7. using  System.Windows.Forms;
  8. using  System.IO;
  9. namespace  TestUploader
  10. {
  11. public  partial course  Form1 : Grade
  12.     {
  13. public  Form1()
  14.         {
  15.             InitializeComponent();
  16.         }
  17. private void  Form1_Load( object  sender, EventArgs due east)
  18.         {
  19.         }

Bated from the default imports, I have added merely Organisation.IO to the list. This being necessary to support working with files. The namespace and class declarations are in the default configuration. In addition to System.IO, the projection likewise adds in a spider web reference pointing to the File Uploader web service, the reference is given the alias of Uploader.

The next bit of lawmaking in the class is private method used to prepare the file for submittal to the web service and to actually brand that submittal. The lawmaking beneath is annotated to describe the activity but the essential parts of the operation are to check the file size to run across if the spider web service will accept the file (by default, the spider web server will accept uploads smaller than iv MB in size, the web config file must be updated in order to support larger uploads), and to convert the file to a byte array. When everything is ready, the byte assortment and the name of the file including the extension is passed to an instance of the spider web service web method.

Note that, when setting upwards the demo, you will have remove and add the spider web reference back into the projection in order for it to work for you.

  1. private void  UploadFile( string  filename)
  2. {
  3. endeavour
  4.     {
  5.         String strFile = Organisation.IO.Path.GetFileName(filename);
  6.         TestUploader.Uploader.FileUploader srv =new
  7.         TestUploader.Uploader.FileUploader();
  8.         FileInfo fInfo =new  FileInfo(filename);
  9. long  numBytes = fInfo.Length;
  10. double  dLen = Convert.ToDouble(fInfo.Length / 1000000);
  11. if  (dLen < 4)
  12.         {
  13.             FileStream fStream =new  FileStream(filename,
  14.             FileMode.Open, FileAccess.Read);
  15.             BinaryReader br =new  BinaryReader(fStream);
  16. byte [] information = br.ReadBytes(( int )numBytes);
  17.             br.Close();
  18. cord  sTmp = srv.UploadFile(data, strFile);
  19.             fStream.Close();
  20.             fStream.Dispose();
  21.             MessageBox.Bear witness("File Upload Condition: "  + sTmp, "File Upload" );
  22.         }
  23. else
  24.         {
  25.              MessageBox.Bear witness("The file selected exceeds the size limit for uploads." , "File Size" );
  26.          }
  27.     }
  28. take hold of  (Exception ex)
  29.     {
  30.          MessageBox.Testify(ex.Bulletin.ToString(),"Upload Fault" );
  31.     }
  32. }

Following the UploadFile method, the next bit of code is used to handle the browse button'south click event. This lawmaking is used but to display an open file dialog to the user and to accept the file selected through that dialog and display the file name in the form'southward file name text box.

  1. individual void  btnBrowse_Click( object  sender, EventArgs e)
  2. {
  3.     openFileDialog1.Title ="Open up File" ;
  4.     openFileDialog1.Filter ="All Files|*.*" ;
  5.     openFileDialog1.FileName ="" ;
  6. try
  7.     {
  8.         openFileDialog1.InitialDirectory ="C:\\Temp" ;
  9.     }
  10. catch
  11.     {
  12.     }
  13.     openFileDialog1.ShowDialog();
  14. if  (openFileDialog1.FileName == "" )
  15. render ;
  16. else
  17.         txtFileName.Text = openFileDialog1.FileName;
  18. }

The class wraps up with the push click event handler for the Upload button. This handler merely checks for text in the file name text box and, if something is there, it sends the value to the Upload method.

  1. private void  btnUpload_Click( object  sender, EventArgs east)
  2. {
  3. if  (txtFileName.Text != string .Empty)
  4.         UploadFile(txtFileName.Text);
  5. else
  6.         MessageBox.Show("You lot must select a file first." , "No File Selected" );
  7. }

That wraps upwards all of the client and server side lawmaking necessary to upload any sort of file to a server from a Win Forms application.

SummaryThis article was intended to demonstrate an easy approach to uploading any sort of a file to a spider web server from a Win Forms application. This example uses the default upload size of 4096 KB, if you lot need to upload larger files, yous will need to change this value past irresolute the httpRuntime maxRequestLength property to the desired value; at the same fourth dimension you may need to increase the executionTimeout property to a greater value as well in order to back up longer upload times. Take intendance when altering the values every bit Microsoft has established the default iv MB limit to provide some safety against attempts to upload extremely large files that may hamper access to the server.

conroyproadite.blogspot.com

Source: https://www.c-sharpcorner.com/article/upload-any-type-of-file-through-a-C-Sharp-web-service/

0 Response to "file upload c# .net core 2 table"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel