Swift实现多目录文档批量获取并上传至服务器方法咨询
Swift 获取多目录文档并上传服务器
一、扫描指定目录下的所有文档
用FileManager遍历目标目录,筛选出需要的文档类型(比如.pdf、.doc、.txt等),示例代码如下:
import Foundation // 定义要扫描的目录路径(示例包含Documents目录和自定义目录) let targetDirectories: [URL] = [ FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!, URL(fileURLWithPath: "/Users/xxx/CustomDocuments") // 替换为你的目标目录路径 ] // 定义允许的文档扩展名 let allowedExtensions = ["pdf", "doc", "docx", "txt", "pages"] func scanDocumentsInDirectories() -> [URL] { var allDocuments: [URL] = [] for directory in targetDirectories { guard let enumerator = FileManager.default.enumerator(at: directory, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) else { continue } for case let fileURL as URL in enumerator { let fileExtension = fileURL.pathExtension.lowercased() guard allowedExtensions.contains(fileExtension) else { continue } // 校验是否为普通文件而非目录 var isRegularFile: ObjCBool = false if FileManager.default.fileExists(atPath: fileURL.path, isDirectory: &isRegularFile), isRegularFile.boolValue { allDocuments.append(fileURL) } } } return allDocuments } // 调用方法获取所有文档 let documents = scanDocumentsInDirectories() print("找到\(documents.count)个文档")
注意点:
- 若需访问iOS系统的外部存储(比如文件App中的目录),需在
Info.plist中配置对应权限,比如UIFileSharingEnabled或NSFileProviderDomainUsageDescription。 - 遍历目录时跳过隐藏文件,避免无效文件被选中。
二、上传文档到服务器
使用URLSession实现多文件上传,采用服务器通用的multipart/form-data格式,示例代码如下:
func uploadDocuments(_ documents: [URL], to serverURL: URL) { let session = URLSession.shared let boundary = "Boundary-\(UUID().uuidString)" var request = URLRequest(url: serverURL) request.httpMethod = "POST" request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") // 构建请求体 let body = NSMutableData() for document in documents { let fileName = document.lastPathComponent let mimeType = getMimeType(for: document) // 添加文件分隔符 body.append("--\(boundary)\r\n".data(using: .utf8)!) // 添加文件字段信息 body.append("Content-Disposition: form-data; name=\"files[]\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!) body.append("Content-Type: \(mimeType)\r\n\r\n".data(using: .utf8)!) // 添加文件数据 if let fileData = try? Data(contentsOf: document) { body.append(fileData) } body.append("\r\n".data(using: .utf8)!) } // 添加结束分隔符 body.append("--\(boundary)--\r\n".data(using: .utf8)!) request.httpBody = body as Data // 发起上传请求 let task = session.dataTask(with: request) { data, response, error in if let error = error { print("上传失败:\(error.localizedDescription)") return } guard let httpResponse = response as? HTTPURLResponse, (200...299).contains(httpResponse.statusCode) else { print("服务器响应异常") return } if let data = data, let responseString = String(data: data, encoding: .utf8) { print("上传成功,响应:\(responseString)") } } task.resume() } // 辅助方法:获取文件MIME类型 func getMimeType(for fileURL: URL) -> String { if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, fileURL.pathExtension as CFString, nil)?.takeRetainedValue() { if let mimeType = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { return mimeType as String } } return "application/octet-stream" // 默认类型 } // 调用上传方法(替换为你的服务器接口地址) let serverURL = URL(string: "https://your-server.com/upload")! uploadDocuments(documents, to: serverURL)
注意点:
- 替换
serverURL为你的实际服务器上传接口地址。 - 大文件建议使用后台上传配置(
URLSessionConfiguration.background(withIdentifier:)),避免APP退后台后上传中断。 - iOS端需配置网络权限:若服务器为HTTP协议,需在
Info.plist中添加NSAppTransportSecurity相关配置;推荐优先使用HTTPS协议。
内容的提问来源于stack exchange,提问作者Ds Pattaiya
相关产品推荐
相关产品推荐

