将数据附加到帖子正文并上传到api



我正在调用一个api,并传递一些参数,包括从icloud获取一些文件,如pdf、doc、docx并调用该api。

现在我正在从icloud中挑选一些文件,需要传递给api调用。问题是我的选择文件(pdf或doc(没有转换为nsdata,字节数为0。所以它没有返回到我的身体参数。帮助我找出哪里做了错误的

我的代码:

func uploadthefileToserver(){
if let url = URL(string: "https://www.exampleurl/api"){
var request = URLRequest(url: url)
let boundary:String = "Boundary-(UUID().uuidString)"
// let request = NSMutableURLRequest(url:myUrl! as URL);
request.httpMethod = "POST"
request.timeoutInterval = 10
request.setValue("multipart/form-data; boundary=(boundary)", forHTTPHeaderField: "Content-Type")
let postJobData:[String:Any] = ["UserId":"107","name":"hardcodevalue"]
var dataFile: Data = Data()
print(fullDestPath)   ///Users/sathish/Library/Developer/CoreSimulator/Devices/4464E7A8-0F38-4802-B645-19721D251054/data/Containers/Data/Application/714B1B8E-5872-42B9-B963-B0C51C9403D7/Documents/NewFileiCloud/iOS.DOCX"
do{
dataFile = try NSData.init(contentsOf: URL(fileURLWithPath: fullDestPath, isDirectory: true)) as Data
print(dataFile)
}catch{
print(error)
}
if(dataFile==nil)  { return; }
print(dataFile) //0 bytes
request.httpBody = createBodyWithParameters(parameters: postJobData, filePathKey: "Resume", FileData: dataFile as NSData , boundary: boundary) as Data
print(postJobData)
print(dataFile)
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
print("error=(error)")
return
}else if let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue){
print("****** response data = (responseString)")
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
print(json)
let status = json!["Success"] as! String
let errMessage = json!["Message"] as? String
DispatchQueue.main.async() {
if status == "1"{
print(errMessage)
}else{
print(errMessage)
}
}
}catch{
print(error)
}
}
}; task.resume()
}
}

不确定我哪里做错了。我放了一些打印函数作为参考。

主要部件:

dataFile = try NSData.init(contentsOf: URL(fileURLWithPath:
fullDestPath, isDirectory: true)) as Data
request.httpBody = createBodyWithParameters(parameters: postJobData,
filePathKey: "Resume", FileData: dataFile as NSData , boundary:
boundary) as Data

感谢

更新:

func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
print("url = (urls)")
filePathUrl = urls
print(filePathUrl)
for urll in filePathUrl{
filepath = filePathUrl[0] as! URL
print(filepath)
filePathString = filepath.path
urlstr = NSURL(fileURLWithPath: filePathString).lastPathComponent!
print(urlstr)
// Data object to fetch weather data
do {
let weatherData = try NSData(contentsOf: filepath, options: NSData.ReadingOptions())
print(weatherData)
} catch {
print(error)
}
}
let destPath:NSArray = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as NSArray
let fileManager = FileManager.default
print(destPath, "n")
documentDir = destPath[0] as? NSString
let filePath = documentDir?.appendingPathComponent("NewFileiCloud") as! NSString
//  if fileManager.fileExists(atPath: filePath as String){
do {
// try fileManager.createDirectory(atPath: filePath as String, withIntermediateDirectories: false, attributes: nil)
fullDestPath = filePath.appendingPathComponent(urlstr)
print(fullDestPath!) ///Users/sathish/Library/Developer/CoreSimulator/Devices/4464E7A8-0F38-4802-B645-19721D251054/data/Containers/Data/Application/E41634D7-681A-4C09-B3EF-5782CECCF4B0/Documents/NewFileiCloud/filke.pdf
do{
try fileManager.copyItem(atPath: filePathString!, toPath: fullDestPath)
}catch{
print("n")
print(error)
}
}catch{
print(error)
}
// }
// ------- This is the path of the application stored filepath -------------- //
filePathLabel.text = fullDestPath
// ------------------- ---------------------------------//
// Read a file content
//     fileContent = fileManager.contents(atPath: fullDestPath as String ) as! NSData
//       print(fileContent)
uploadthefileToserver()
}
func createBodyWithParameters(parameters: [String: Any]?, filePathKey: String?, FileData: NSData, boundary: String) -> NSData {
let body = NSMutableData();
if parameters != nil {
for (key, value) in parameters! {
body.appendString(string:"--(boundary)rn")
body.appendString(string: "Content-Disposition: form-data; name="(key)"rnrn")
body.appendString(string: "(value)rn")
}
}
return body
let filename = fullDestPath
let mimetype = "pdf/docx/text"
body.appendString(string: "--(boundary)rn")
body.appendString(string: "Content-Disposition: form-data; name="(filePathKey!)"; filename="(filename)"rn")
body.appendString(string: "Content-Type: (mimetype)rnrn")
body.append(FileData as Data)
body.appendString(string: "rn")
body.appendString(string: "--(boundary)--rn")
return body
}

您正在尝试这样做,

  1. 将PDFURL转换为数据

  2. 将数据转换为.PDF

  3. 将该.PDF存储在Doc.Dir.中

  4. 正在从Doc.Dir检索.PDF并传递到服务器。

对于上述任务,您必须在Doc.Dir中创建文件夹NewFileiCloud。然后,将pdfUrl转换为data,并将数据写入.pdf文件,然后,从doc.dir获得.pdf路径,将其转换为Data并传递给server

我已经为你做了样品。这会让你满意的。

override func viewDidAppear(_ animated: Bool) {
// I have did sample for you by taking .pdf from bundle.
if let pathPDF = Bundle.main.path(forResource: "sample", ofType: "pdf") {
let path = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let documentDirectoryPath:String = path[0]
let fileManager = FileManager()
var destinationURLForFile = URL(fileURLWithPath: documentDirectoryPath.appending("/NewFileiCloud"))
do {
//You have to create directory with above name.
try fileManager.createDirectory(at: destinationURLForFile, withIntermediateDirectories: true, attributes: nil)
destinationURLForFile.appendPathComponent("reader.pdf")
//YOUR PDF URL [pathPDF [my bundle path, you have to give your URL]] to DATA
let pdfData = try Data(contentsOf: URL(fileURLWithPath: pathPDF))  
// WRITE ITS CONTENT to Doc.Dir.
try pdfData.write(to: destinationURLForFile, options:.atomic)
//ASSIGN PATH TO GLOBAL URL VARIABLE
fullPAth = destinationURLForFile

print("conclude     ", destinationURLForFile)
uploadToServer()
}
catch(let error){
print(error)
}
}
}

func uploadToServer() {
.....
do {
// Here you can get PDF contents as Data.
// With this Data, you can pass to Server Side.
let pdfPOSTData = try Data(contentsOf: fullPAth!)
}
catch let e{
print("Catch_Not_worlk    ",  e)
}
......
}

相关内容

  • 没有找到相关文章

最新更新