主要是参考MSDN的范例,简单的给出前台请求后台的处理:
public string uploadfile() { HttpContext.Response.ContentType = "application/json"; if (Request.Files.Count == 0) { return new { success = false, err = "没有找到文件" }.ToJson(); } string fileName = Request.Files[0].FileName; string ftpServerIP = asolution.config.Object.FileServers.FindByName("ftp").Host; //框架web.config 配置的ftpip用户名和密码 string ftpUserID = asolution.config.Object.FileServers.FindByName("ftp").Uid; string ftpPassword = asolution.config.Object.FileServers.FindByName("ftp").Pwd; string fileType = fileName.Substring(fileName.LastIndexOf('.')).ToLower(); string fileFolder = "files"; if (fileType == ".jpg" || fileType == "bmp" || fileType == "jpeg" || fileType == "gif" || fileType == "png") { fileFolder = "images"; } else if (fileType == ".avi" || fileType == ".swf") { fileFolder = "videos"; } string uri = ftpServerIP + "/editorUpload/" + fileFolder +"/"+fileName; FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); reqFTP.KeepAlive = false; reqFTP.Method = WebRequestMethods.Ftp.UploadFile; reqFTP.UseBinary = true; reqFTP.ContentLength = Request.Files[0].ContentLength; int buffLength = 2048; var fs = Request.Files[0].InputStream; byte[] buff = new byte[buffLength]; int contentLen; try { Stream strm = reqFTP.GetRequestStream(); contentLen = fs.Read(buff, 0, buffLength); while (contentLen != 0) { strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } strm.Close(); fs.Close(); } catch(Exception e) { return new { err = e, msg = "" }.ToJson(); } return new { err = "", msg = new { url =ftpServerIP+"//editorUpload//" + fileFolder +"//"+fileName, localname = Request.Files[0].FileName } }.ToJson(); }