我经历了很多帖子但是不满意,目前我正在使用File Explorer Framework
并且工作正常,但是当我选择一个文件时(文件可以是pdf,文档或任何文本文件),然后我将如何在服务器上传该文件?
let fileExplorer = FileExplorerViewController()
fileExplorer.canChooseFiles = true //specify whether user is allowed to choose files
fileExplorer.canChooseDirectories = false //specify whether user is allowed to choose directories
fileExplorer.allowsMultipleSelection = true //specify whether user is allowed to choose multiple files and/or directories
fileExplorer.delegate = self
self.present(fileExplorer, animated: true, completion: nil)
及其委托方法
public func fileExplorerViewController(_ controller: FileExplorerViewController, didChooseURLs urls: [URL]) {
//Your code here
}
现在如何通过委托方法获取文件网址来上传文件?
任何帮助将不胜感激。
由于
答案 0 :(得分:3)
你可以使用documentpicker
fileprivate func p_documentclicked() {
let importMenu = UIDocumentMenuViewController(documentTypes: ["public.text", "public.data","public.pdf", "public.doc"], in: .import)
importMenu.delegate = self
self.present(importMenu, animated: true, completion: nil)
}
然后它有一个委托方法
internal func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentAt url: URL) {
let cico = url as URL
print(cico)
self.downloadfile(URL: cico as NSURL)
}
获得URL
后,您可以下载文件,然后上传文件。
fileprivate func downloadfile(URL: NSURL) {
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: nil, delegateQueue: nil)
var request = URLRequest(url: URL as URL)
request.httpMethod = "GET"
let task = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error == nil) {
// Success
let statusCode = response?.mimeType
print("Success: \(String(describing: statusCode))")
DispatchQueue.main.async(execute: {
self.p_uploadDocument(data!, filename: URL.lastPathComponent!)
})
// This is your file-variable:
// data
}
else {
// Failure
print("Failure: %@", error!.localizedDescription)
}
})
task.resume()
}
您可以使用此方法上传doc和pdf文件:
fileprivate func p_uploadDocument(_ file: Data,filename : String) {
let parameters = ["yourParam" : "sample text"]
let fileData = file
let URL2 = try! URLRequest(url: "your api", method: .post, headers: ["Authorization" :"your auth key"])
Alamofire.upload(multipartFormData: { (multipartFormData) in
multipartFormData.append(fileData as Data, withName: "upfile", fileName: filename, mimeType: "text/plain")
for (key, value) in parameters {
multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
}
}, with: URL2 , encodingCompletion: { (result) in
switch result {
case .success(let upload, _, _):
print("s")
upload.responseJSON {
response in
if let JSON = response.result.value as? [String : Any]{
let messageString = JSON["message"] as? String
// use the JSON
}else {
//error hanlding
}
}
}
case .failure(let encodingError):
// error handling
}
}
)
}
答案 1 :(得分:0)
我用它来上传mp3。而且它的目标-c,我希望你可以轻松地将它转换为快速。
- (void) uploadFileToServer{
NSData *audioData = [NSData dataWithContentsOfURL:recorder.url];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// serializerWithReadingOptions:NSJSONReadingAllowFragments];
[manager POST:@"your_url" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:audioData
name:@"audio_file"
fileName:@"MyAudioMemo.m4a" mimeType:@"audio/m4a"];
[formData appendPartWithFormData:[sender dataUsingEncoding:NSUTF8StringEncoding]
name:@"sender"];
[formData appendPartWithFormData:[receiver dataUsingEncoding:NSUTF8StringEncoding]
name:@"receiver"];
[formData appendPartWithFormData:[senderLanguage dataUsingEncoding:NSUTF8StringEncoding]
name:@"sender_language"];
[formData appendPartWithFormData:[receiverLanguage dataUsingEncoding:NSUTF8StringEncoding]
name:@"receiver_language"];
// etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
if ([responseObject isKindOfClass:[NSData class]]) {
NSError *jsonError = nil;
NSString *str=[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(@"Response = %@",str);
NSDictionary *JSON = [NSJSONSerialization JSONObjectWithData:(NSData *)responseObject
options:kNilOptions
error:&jsonError];
NSLog(@"\nDictionary : %@", JSON);
}
// NSLog(@"Response: %@", responseObject);
// NSDictionary *dict = (NSDictionary *) responseObject;
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(@"Error: %@", error);
}];
}