Sliverlight allows you to upload and download files.

Source: Internet
Author: User

(1) Upload attachments

Silverlight code:

Private void button#click (Object sender, routedeventargs E)
{
Openfiledialog dialog = new openfiledialog ();
If (dialog. showdialog (). value)
{
// Select the uploaded file
Fileinfo file = dialog. file;
Stream stream = file. openread ();
Stream. Position = 0;
Byte [] buffer = new byte [stream. Length + 1];
// Read the file into a byte array
Stream. Read (buffer, 0, buffer. Length );
String fileextention = file. extension;
// Call the service for upload
Servicereference1.uploadfilesoapclient upfile = new uploadfilesoapclient ();
Upfile. uploadfileasync (buffer, fileextention );
Upfile. uploadfilecompleted + = new eventhandler <uploadfilecompletedeventargs> (upfile_uploadfilecompleted );

}
Else
{
MessageBox. Show ("select a file! ");
}
}
Void upfile_uploadfilecompleted (Object sender, uploadfilecompletedeventargs E)
{
MessageBox. Show ("Upload successful! ");
}

 

WebService code:

[Webmethod]
Public int uploadfile (byte [] filebyte, string fileextention)
{
// File storage path
String filepath = string. Format (@ "D: \ example {0}", fileextention );
// Delete an object if it already exists
If (file. exists (filepath ))
File. Delete (filepath );
// Create a file stream instance for writing files
Filestream stream = new filestream (filepath, filemode. createnew );
// Write a file
Stream. Write (filebyte, 0, filebyte. Length );
Stream. Close ();
Return filebyte. length;
}

(2)

Public void uploadfile (ebilltype, int nbillid, byte [] arrfilebyte, string sfilename, string sfiletype, string sremarks)
{
Filestream objfilestream = NULL;
Try
{

// Name the folder by Time
Sfilename = sfilename. substring (0, sfilename. lastindexof (".")-1) + (datetime. Now. tostring ("yyyymmddhhssmm "));
// File storage path
String sfilepath = string. Format (@ "D: \ mywork \ MRP system \ MRP \ mrpservice \ files \ {0} {1}", sfilename, sfiletype );

// String fileextention = file. extension;
// Sfiletype = sfiletype. substring (sfiletype. lastindexof (".") + 1). tolower ();
// Call the service to upload supported file formats
If (sfiletype! = ". Xls" & sfiletype! = ". Doc" & sfiletype! = ". Pdf ")
{
Throw new exception ("the format of the uploaded file is not supported! ");
}
// Delete an object if it already exists
If (file. exists (sfilepath ))
File. Delete (sfilepath );
// Create a file stream instance for writing files
// String swebconfig = system. configuration. configurationsettings. deleettings ["attachdbfilename"];
// String swebconfig = "D: \ mywork \ MRP system \ MRP \ mrpservice ";

Objfilestream = new filestream (sfilepath, filemode. createnew );
// Write a file
Objfilestream. Write (arrfilebyte, 0, arrfilebyte. Length );
Objfilestream. Close ();

// Save to database
Cuploadfile objuploadfile = new cuploadfile (ebilltype, nbillid, base. loguserid, base. logusername, base. logusercode, base. logdeptid, base. logdeptname );
Objuploadfile. filename = sfilename;
Objuploadfile. filepath = sfilepath;
Objuploadfile. filesize = arrfilebyte. length;
Objuploadfile. filetype = sfiletype;

Uploadfiledal. Save (objuploadfile );

}
Catch (exception ex)
{
Throw ex;
}
Finally
{
Objfilestream = NULL;
}
}

Download file:

Public void processrequest (httpcontext context)
{
String filename = context. Request. querystring ["FILENAME"]; // file name saved by the client
Filename = httputility. urldecode (filename );
String filepath = context. server. mappath ("Data/" + filename); // path
Fileinfo = new fileinfo (filepath );
If (fileinfo. exists)
{
Byte [] buffer = new byte [102400];
Context. response. Clear ();

Filestream istream = file. openread (filepath );
Long datalengthtoread = istream. length; // obtain the total size of the downloaded file

Context. response. contenttype = "application/octet-stream ";
Context. response. addheader ("content-disposition", "attachment; filename =" +
Httputility. urlencode (filename, system. Text. encoding. utf8 ));
While (datalengthtoread> 0 & context. response. isclientconnected)
{
Int lengthread = istream. Read (buffer, 0, convert. toint32 (102400); // 'read size

Context. response. outputstream. Write (buffer, 0, lengthread );
Context. response. Flush ();
Datalengthtoread = datalengthtoread-lengthread;
}
Context. response. Close ();
Context. response. End ();

}

}

Public bool isreusable
{
Get
{
Return false;
}
}
}
}

 

When we create and play this class, you can click the Download button to write events to call this class to download files! However, the condition is that your file is stored in a fixed folder. You can download the file only by finding the path.

Private void hyperlinkbutton_click (Object sender, routedeventargs E)
{
String fileaddressofneeded = 20.1.txt "; // name of the file to be downloaded

Hyperlinkbutton hlbutton = sender as hyperlinkbutton;
VaR client = new WebClient ();
VaR u = new uri (string. Format ("{0}/http://www.cnblogs.com/Handler/DownLoadFileHandler.ashx? Filename = {1} ", client. baseaddress, fileaddressofneeded), urikind. relativeorabsolute );
Hlbutton. navigateuri = u;
}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.