How to upload photo to a server from .net winforms?
I have created a window form appl开发者_如何学JAVAication in C#. There is a user registration section where user details are filled and a photo is uploaded. How to upload photo a common location in server not in client system. I need to upload the picture of user to a location in server so that the website section of the application can show the picture in the profile of user.
I would actually store the information including the picture in the database, so it's available from all your other applications.
if you simply want to copy a raw file from client computer to a centralized location, as a starting point:
private void button1_Click(object sender, EventArgs e)
{
WebClient myWebClient = new WebClient();
string fileName = textBox1.Text;
string _path = Application.StartupPath;
MessageBox.Show(_path);
_path = _path.Replace("Debug", "Images");
MessageBox.Show(_path);
myWebClient.UploadFile(_path,fileName);
}
private void btnBrowse_Click(object sender, EventArgs e)
{
OpenFileDialog ofDlg = new OpenFileDialog();
ofDlg.Filter = "JPG|*.jpg|GIF|*.gif|PNG|*.png|BMP|*.bmp";
if (DialogResult.OK == ofDlg.ShowDialog())
{
textBox1.Text = ofDlg.FileName;
button1.Enabled = true;
}
else
{
MessageBox.Show("Go ahead, select a file!");
}
}
Maybe best way is to use an FTP Server ,if you can install it . Than you can upload file's using this code
FileInfo toUpload = new FileInfo("FileName");
System.Net.FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://serverip/FileName");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("UserName","Password");
Stream ftpStream = request.GetRequestStream();
FileStream file = File.OpenRead(files);
int length = 1024;
byte[] buffer = new byte[length];
int bytesRead = 0;
do
{
bytesRead = file.Read(buffer, 0, length);
ftpStream.Write(buffer, 0, bytesRead);
}
while (bytesRead != 0);
file.Close();
ftpStream.Close();
upload a file to FTP server using C# from our local hard disk.
private void UploadFileToFTP()
{
FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create("ftp://www.server.com/sample.txt");
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential("user", "pass");
byte[] b = File.ReadAllBytes(@"E:\sample.txt");
ftpReq.ContentLength = b.Length;
using (Stream s = ftpReq.GetRequestStream())
{
s.Write(b, 0, b.Length);
}
FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();
if (ftpResp != null)
{
if(ftpResp.StatusDescription.StartsWith("226"))
{
Console.WriteLine("File Uploaded.");
}
}
}
精彩评论