gpt4 book ai didi

ios - 使用 Swift 4 将 Pdf、Docx 和图像文件上传到服务器

转载 作者:搜寻专家 更新时间:2023-10-31 21:58:51 28 4
gpt4 key购买 nike

我是 swift 的新手,我一直在尝试从 Iphone 的本地存储上传 pdf、docx 和图像文件。我已经编写了一个代码,但它不起作用,而且我一直从响应中得到状态代码:415。这是我的代码:

func uploadfileToServer(completed: @escaping () -> ()){

let theTitle = labelTitle.text


guard let url = URL(string: "http://www.--------.com/assignment/post") else {return}
var request = URLRequest.init(url: url)
request.httpMethod = "POST"

request.addValue("cf7ab8c9d4efae82b575eabd6bec76cbb86c6108391e036387f3dd5356a582171519367747000", forHTTPHeaderField: "api_key")




let boundary = generateBoundaryString()


// Set Content-Type in HTTP header.
let boundaryConstant = boundary // This should be auto-generated.
let contentType = "multipart/form-data; boundary=" + boundaryConstant

let directory = NSTemporaryDirectory()
let fileName = NSUUID().uuidString

// This returns a URL? even though it is an NSURL class method
let fullURL = NSURL.fileURL(withPathComponents: [directory, fileName])



let fileNamee = fullURL?.path
let mimeType = "text/csv"
let fieldName = "uploadFile"

request.setValue(contentType, forHTTPHeaderField: "Content-Type")



var dataString = "--\(boundaryConstant)\r\n"


dataString += "\r\n"
dataString += "--\(boundaryConstant)--\r\n"

var theBody = Data()



let sectionID : String?
sectionID = nil
let str = "user_id=\(savedsesuid!)" + "&school_id=" + SCHOOL_ID + "&class_id=" + classID + "&section_id=\(sectionID)" + "&subject_id=\(id)"



if let b = str.data(using: .utf8) {
theBody.append(b)
}

let str1 = "&atitle=" + theTitle! + "&class_id=" + classID

if let c = str1.data(using: .utf8){
theBody.append(c)
}


let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
var filePath = documentDirectory.appendingFormat("/")
filePath = filePath.appendingFormat("/Users/prashanna/Desktop/ebusiness_topic_1_handout.pdf")
let pdfData = NSData(contentsOfFile: filePath)

let file = "&afile=" + "\(pdfData)"

if let d = file.data(using: .utf8){
theBody.append(d)
}

print(theBody)



request.httpBody = theBody

URLSession.shared.dataTask(with: request) { (data, response, error) in
print(response)
if let httpResponse = response as? HTTPURLResponse {
let statuscode = httpResponse.statusCode
if statuscode == 401{
self.displayMessage(userMessage: "Sending Failed")


}else if statuscode == 200{
if error == nil{
do{
self.displayMessage(userMessage: "File Successfully Uploaded!")
DispatchQueue.main.async {
completed()

}

}

}
}
}
}.resume()



}

func generateBoundaryString() -> String {
return "Boundary-\(NSUUID().uuidString)"
}

有些解决方案告诉我将文件转换为数据,然后将其发送到服务器,而有些则说直接将文件路径添加到您的正文中。需要帮助!

最佳答案

一个根本错误是您使用的是 dataTask 而不是 uploadTask在您的 URLSession 实例上,例如uploadTask(with:from:completionHandler:)

body 数据的构建

这是我自己的代码中的一个通用示例(如以下评论中所要求的),说明了如何构建主体数据:

// imagesURLS is an optional array of URLs, i.e. imageURLS:[URL]?

if let imgURLs = imagesURLS {
for f in imgURLs {
let filename = f.lastPathComponent
let splitName = filename.split(separator: ".")
let name = String(describing: splitName.first)
let filetype = String(describing: splitName.last)

let imgBoundary = "\r\n--\(boundary)\r\nContent-Type: image/\(filetype)\r\nContent-Disposition: form-data; filename=\(filename); name=\(name)\r\n\r\n"

if let d = imgBoundary.data(using: .utf8) {
bodyData.append(d)
}

do {
let imgData = try Data(contentsOf:f, options:[])
bodyData.append(imgData)
}
catch {
// can't load image data
}

}
}
let closingBoundary = "\r\n--\(boundary)--"
if let d = closingBoundary.data(using: .utf8) {
bodyData.append(d)
}

循环意味着每个数据项(在本例中为图像)之前都有一个边界字符串,在最后一个数据项之后添加结束边界字符串(即以双连字符结​​尾的字符串)。

关于ios - 使用 Swift 4 将 Pdf、Docx 和图像文件上传到服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49731100/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com