1 public class FileUploadArgs : EventArgs 2 { 3 public string FileName { get; set; } 4 public Exception Ex { get; set; } 5 } 6 public class FileUploader 7 { 8 9 #region Member Variables 10 11 /// <summary> 12 /// The web client used to asynchronously upload data. 13 /// </summary> 14 private WebClient webClient = new WebClient(); 15 16 /// <summary> 17 /// Acts as an index in the file array and is used by multiple event 18 /// handlers. 19 /// 20 /// Upload process starts with currentFileIndex = 0, and when the 21 /// first file is successfully uploaded, the index is incremented. 22 /// 23 /// When the index is gets above the length of the array, then it 24 /// is evident that all the files have been uploaded. 25 /// 26 /// </summary> 27 private int currentFileIndex; 28 29 FileInfo[] _fileInfo; 30 string[] reNameFiles; 31 string folderName; 32 33 #endregion 34 #region Business Logic 35 36 public FileUploader() 37 { 38 webClient.OpenWriteCompleted += webClient_OpenWriteCompleted; 39 webClient.WriteStreamClosed += webClient_WriteStreamClosed; 40 } 41 ~FileUploader() 42 { 43 webClient.OpenWriteCompleted -= webClient_OpenWriteCompleted; 44 webClient.WriteStreamClosed -= webClient_WriteStreamClosed; 45 } 46 private void webClient_OpenWriteCompleted(object s, OpenWriteCompletedEventArgs e) 47 { 48 //Make sure that the file to be uploaded is not null. 49 if (_fileInfo[currentFileIndex] != null) 50 { 51 //Create a file upload argument to pass to events. 52 FileUploadArgs fileUploadArgs = new FileUploadArgs() { FileName = _fileInfo[currentFileIndex].Name }; 53 try 54 { 55 if (OnFileUploadStarted != null) 56 { 57 OnFileUploadStarted(this, fileUploadArgs); 58 } 59 60 //Open a file stream corresponding to the 61 Stream fileStream = _fileInfo[currentFileIndex].OpenRead(); 62 PushData(fileStream, e.Result); 63 64 //Close the streams. 65 e.Result.Close(); 66 fileStream.Close(); 67 fileStream.Dispose(); 68 } 69 catch (Exception ex) 70 { 71 if (OnFileUploadError != null) 72 { 73 fileUploadArgs.Ex = new Exception("此文件正在使用,请关闭后重新选择!", ex); 74 OnFileUploadError(this, fileUploadArgs); 75 } 76 } 77 78 } 79 } 80 private void webClient_WriteStreamClosed(object s, WriteStreamClosedEventArgs e) 81 { 82 //ToDo: Output a helpful error. 83 if (e.Error == null) 84 { 85 //Create a file upload argument to pass to events. 86 FileUploadArgs fileUploadArgs = new FileUploadArgs() { FileName = _fileInfo[currentFileIndex].Name }; 87 88 if (OnFileUploadCompleted != null) 89 { 90 OnFileUploadCompleted(this, fileUploadArgs); 91 } 92 93 currentFileIndex++; 94 95 //Try to find the next null object. 96 while (currentFileIndex < _fileInfo.Length && _fileInfo[currentFileIndex] == null) 97 currentFileIndex++; 98 99 //Check to see if there are more files waiting to be uploaded. 100 if (currentFileIndex < _fileInfo.Length) 101 { 102 Uri nextUri = GetUri(_fileInfo[currentFileIndex], reNameFiles[currentFileIndex], folderName); 103 104 //Start another upload. 105 webClient.OpenWriteAsync(nextUri); 106 107 } 108 //All file uploads are complete. 109 else 110 { 111 if (OnAllFilesUploadCompleted != null) 112 { 113 OnAllFilesUploadCompleted(this, fileUploadArgs); 114 } 115 } 116 } 117 } 118 /// <summary> 119 /// This method should only be used for uploading single files. 120 /// </summary> 121 /// <param name="fileInfo">The file to upload</param> 122 /// <param name="projectName">The server side folder where to upload the file.</param> 123 public void UploadFile(FileInfo fileInfo, string reNameFile, string folderName) 124 { 125 UploadFiles(new FileInfo[] { fileInfo }, new string[] { reNameFile }, folderName); 126 } 127 128 public void UploadFiles(FileInfo[] fileInfo, string[] reNameFiles, string folderName) 129 { 130 131 //ToDo: Throw an error when fileInfo is null. 132 if (fileInfo == null) 133 return; 134 135 _fileInfo = fileInfo; 136 137 this.reNameFiles = reNameFiles; 138 this.folderName = folderName; 139 140 currentFileIndex = 0; 141 142 //Find the first non-null file info. 143 while (currentFileIndex < fileInfo.Length && fileInfo[currentFileIndex] == null) 144 currentFileIndex++; 145 146 //If all files were null, exit the method. 147 if (currentFileIndex == fileInfo.Length) 148 { 149 //ToDo: might need an exception here. On the other, silent exit is not 150 //such a bad thing, since if all files are null then basically without 151 //uploading any files, the method is done. 152 return; 153 } 154 155 //Start file upload from that first non-null file. 156 Uri uri = GetUri(fileInfo[currentFileIndex], reNameFiles[currentFileIndex], folderName); 157 158 webClient.OpenWriteAsync(uri); 159 } 160 161 #endregion 162 163 164 #region Helper Methods 165 166 private static Uri GetUri(FileInfo fileInfo, string reName, string folderName) 167 { 168 string http = UriUtil.GetUrl("Operation.ashx"); 169 UriBuilder uriBuilder = new UriBuilder(http); 170 uriBuilder.Query = string.Format("_fileOper=upload&_fileName={0}&_foldername={1}", reName, folderName); 171 return uriBuilder.Uri; 172 } 173 174 private void PushData(Stream input, Stream output) 175 { 176 byte[] buffer = new byte[4096]; 177 int bytesRead; 178 179 int totalRead = 0; 180 181 while ((bytesRead = input.Read(buffer, 0, buffer.Length)) != 0) 182 { 183 output.Write(buffer, 0, bytesRead); 184 //Increment the bytes read. 185 totalRead += bytesRead; 186 } 187 } 188 189 #endregion 190 191 192 #region Events and Handlers 193 194 public delegate void AllFilesUploadCompleted(object sender, FileUploadArgs e); 195 public event AllFilesUploadCompleted OnAllFilesUploadCompleted; 196 197 public delegate void FileUploadCompleted(object sender, FileUploadArgs e); 198 public event FileUploadCompleted OnFileUploadCompleted; 199 200 public delegate void FileUploadStarted(object sender, FileUploadArgs e); 201 public event FileUploadStarted OnFileUploadStarted; 202 203 public delegate void FileUploadError(object sender, FileUploadArgs e); 204 public event FileUploadError OnFileUploadError; 205 206 #endregion 207 }
通过以上代码,方便上传文件至服务器进行操作,例如excel导入。
偕行软件欢迎您光临我们的博客
我们致力于打造国内第一个支持直接在线演示的人力资源管理系统!
我们的官网:http://www.udchn.com
我们的空白开发框架:http://60.211.233.210:8088
我们的集团式人力资源管理系统:http://60.211.233.210:8081