当前位置: 首页 > 知识库问答 >
问题:

MYSQL和Swift-上传图像和文件||使用Alamofire会更好吗?

毕浩渺
2023-03-14

我试图上传一个图像和一个文本文件(作为数据上传)。

到目前为止,我可以单独正确上传图像,也可以单独上传文本文件数据。txt成功上传。

现在我需要同时上传图片和.txt文件。。。

我不知道如何在我的IOS应用程序中为此设置参数。。。。

到目前为止,这就是我上传.txt文件的方式(基本上与上传图像的方式相同,但我更改了“文件名”和“mimetype”)

func createBodyWithParameters(parameters: [String : Any]?, filePathKey: String?,filePathKey1: String?, imageDataKey: NSData,imageDataKey1: NSData, boundary: String) -> NSData {

        let body = NSMutableData();

        if parameters != nil {
            for (key, value) in parameters! {
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
        }

        let filename = "post-\(uuid).txt"
        let mimetype = "image/txt"

        body.appendString("--\(boundary)\r\n")
        body.appendString("Content-Disposition: form-data; name=\"\(filePathKey!)\"; filename=\"\(filename)\"\r\n")
        body.appendString("Content-Type: \(mimetype)\r\n\r\n")


        body.append(imageDataKey as Data)

        body.appendString("\r\n")
        body.appendString("--\(boundary)--\r\n")

        return body
    }

现在我不知道如何保存图像和. txt文件与该参数。

然而,这是我上传它的swft代码的其余部分:

 let param = [
            "id" : id,
            "uuid" : uuid,
            "Text" : Text,
            "Title" : Title
           ] as [String : Any]

        let boundary = "Boundary-\(NSUUID().uuidString)"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

        let data: Data = NSKeyedArchiver.archivedData(withRootObject: blogattributedText)


        var imageData = NSData()
        let image = CoverImage
        let width = CGSize(width: self.view.frame.width, height: image.size.height * (self.view.frame.width / image.size.width))
        imageData = UIImageJPEGRepresentation(imageWithImage(image, scaledToSize: width), 0.5)! as NSData

   // ... body
    request.httpBody = createBodyWithParameters(parameters: param, filePathKey: "file",filePathKey1: "file1", imageDataKey: data as NSData,imageDataKey1: imageData as NSData, boundary: boundary) as Data

如果有人需要查看我的代码或不理解我的问题,请让我知道!

提前感谢任何能提供帮助的人!!

共有2个答案

杨景山
2023-03-14

或者,可以使JSONRestAPI的。

  • 将您的记事本文件内容转换为Base64编码字符串。
  • 转换Base64编码字符串中的图像文件。
  • 在请求参数中传递两个Base64编码的字符串。
  • 一旦你在函数参数中得到API文件上的Base64编码字符串。
  • 再次解码Base64字符串并将其存储在内容文件夹中。

https://github.com/AFNetworking/AFNetworking/wiki/Getting-Started-with-AFNetworking

在swift ios中使用AFN网络上传图像

使用AF2.0上传图像

注意-显示图像iOS应用程序,你可以使绝对URL和使用图像缓存类,你可以显示图像。

万俟丁雷
2023-03-14

如果您不想在创建复杂请求的过程中迷失方向,那么像Alamofire这样的第三方库将是明智的。它是由AFNetworking的同一作者编写的,但它是一个本地的Swift库。

因此,Alamofire实现可能如下所示:

func performRequest(urlString: String, id: String, uuid: String, text: String, title: String, blogAttributedText: NSAttributedString, image: UIImage) {

    let parameters = [
        "id" : id,
        "uuid" : uuid,
        "Text" : text,
        "Title" : title
    ]

    let imageData = UIImageJPEGRepresentation(image, 0.5)!

    let blogData = NSKeyedArchiver.archivedData(withRootObject: blogAttributedText)

    Alamofire.upload(
        multipartFormData: { multipartFormData in
            for (key, value) in parameters {
                if let data = value.data(using: .utf8) {
                    multipartFormData.append(data, withName: key)
                }
            }
            multipartFormData.append(imageData, withName: "image", fileName: "image.jpg", mimeType: "image/jpeg")
            multipartFormData.append(blogData, withName: "blog", fileName: "blog.archive", mimeType: "application/octet-stream")
    },
    to: urlString,
    encodingCompletion: { encodingResult in
        switch encodingResult {
        case .success(let upload, _, _):
            upload
                .validate()
                .responseJSON { response in
                    switch response.result {
                    case .success(let value):
                        print("responseObject: \(value)")
                    case .failure(let responseError):
                        print("responseError: \(responseError)")
                    }
            }
        case .failure(let encodingError):
            print("encodingError: \(encodingError)")
        }
    })
}

如果您要自己构建这个请求,我会提出一些建议。首先,由于您正在发送不同类型的文件,您可能需要一些好的类型来封装这些:

struct FilePayload {
    let fieldname: String
    let filename: String
    let mimetype: String
    let payload: Data
}

我也不确定如何理解image/txtmime类型。我可能会使用应用程序/octet流进行归档。

无论如何,请求的构建可以如下所示:

/// Create request.
///
/// - Parameters:
///   - url:                The URL to where the post will be sent.
///   - id:                 The identifier of the entry
///   - uuid:               The UUID of the entry
///   - text:               The text.
///   - title:              The title.
///   - blogAttributedText: The attributed text of the blog entry.
///   - image:              The `UIImage` of the image to be included.
///
/// - Returns: The `URLRequest` that was created

func createRequest(url: URL, id: String, uuid: String, text: String, title: String, blogAttributedText: NSAttributedString, image: UIImage) -> URLRequest {
    let parameters = [
        "id" : id,
        "uuid" : uuid,
        "Text" : text,     // I find it curious to see uppercase field names (I'd use lowercase for consistency's sake, but use whatever your PHP is looking for)
        "Title" : title
    ]

    let boundary = "Boundary-\(NSUUID().uuidString)"

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.setValue("application/json", forHTTPHeaderField: "Accept")  // adjust if your response is not JSON

    // use whatever field name your PHP is looking for the image; I used `image`

    let imageData = UIImageJPEGRepresentation(image, 0.5)!
    let imagePayload = FilePayload(fieldname: "image", filename: "image.jpg", mimetype: "image/jpeg", payload: imageData)

    // again, use whatever field name your PHP is looking for the image; I used `blog`

    let blogData = NSKeyedArchiver.archivedData(withRootObject: blogAttributedText)
    let blogPayload = FilePayload(fieldname: "blog", filename: "blog.archive", mimetype: "application/octet-stream", payload: blogData)

    request.httpBody = createBody(with: parameters, files: [imagePayload, blogPayload], boundary: boundary)

    return request
}

/// Create body of the multipart/form-data request.
///
/// - Parameters:
///   - parameters: The optional dictionary containing keys and values to be passed to web service.
///   - files:      The list of files to be included in the request.
///   - boundary:   The `multipart/form-data` boundary
///
/// - Returns: The `Data` of the body of the request.

private func createBody(with parameters: [String: String]?, files: [FilePayload], boundary: String) -> Data {
    var body = Data()

    if parameters != nil {
        for (key, value) in parameters! {
            body.append("--\(boundary)\r\n")
            body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
            body.append("\(value)\r\n")
        }
    }

    for file in files {
        body.append("--\(boundary)\r\n")
        body.append("Content-Disposition: form-data; name=\"\(file.fieldname)\"; filename=\"\(file.filename)\"\r\n")
        body.append("Content-Type: \(file.mimetype)\r\n\r\n")
        body.append(file.payload)
        body.append("\r\n")
    }

    body.append("--\(boundary)--\r\n")
    return body
}

/// Create boundary string for multipart/form-data request
///
/// - returns:            The boundary string that consists of "Boundary-" followed by a UUID string.

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

哪里

extension Data {

    /// Append string to Data
    ///
    /// Rather than littering my code with calls to `dataUsingEncoding` to convert strings to `Data`, and then add that data to the `Data`, this wraps it in a nice convenient little `Data` extension. This converts using UTF-8.
    ///
    /// - parameter string:       The string to be added to the mutable `Data`.

    mutating func append(_ string: String) {
        if let data = string.data(using: .utf8) {
            append(data)
        }
    }
}

显然这是Swift 3代码,所以我删除了NSMutableData引用。

 类似资料:
  • 问题内容: 我正在尝试上传图片和文本文件(将其上传为数据)。 到目前为止,我可以正确地单独上传图像,也可以成功上传文本文件数据,并以.txt格式成功上传。 现在,我需要同时上传图片和.txt文件… 我不确定如何在我的IOS应用中为此设置参数…。 到目前为止,这就是我上传.txt文件的方式(基本上与我上传图片的方式相同,但是我更改了“文件名”和“ mimetype”) 现在,我不确定如何使用该参数保

  • 我正试图用Alamofire将图像上传到服务器,但我的代码不起作用。这是我的代码: 这是urlRequestWithComponents方法: 这就是我在控制台得到的: 请求{URL:http://tranthanhphongcntt.esy.es/task_manager/IOSFileUpload/ }响应可选({URL:http://tranthanhphongcntt.esy.es/tas

  • 我在试图让Alamofire上传图像时被困了三天。其想法是,Alamofire将使用一些php代码将其发送到服务器。在不同的地方进行了大量的尝试和研究之后,一些代码应该可以工作,但是Alamofire的服务器端文档非常糟糕。 Swift 3最近的更新对明智的回答没有多大帮助... 这是我的Swift 3代码: 这应该上传到服务器上的图像,但我不知道如何正确地将图像保存在服务器上。服务器实际上不需要

  • 我试图上传图像与多个参数使用阿拉莫菲尔多部分与swift 4,但我不能上传图像成功,我得到的回应如下 这是我在上传按钮事件中调用的函数。 当我转换图像使用UIImagePNG表示与相同的方法只是改变一行 MultipartFormData.append(ImageData!,带名称:图像,文件名:image.png,mimeType:图像/png) 它会给我这样的感觉 请帮帮我!!

  • 我正在使用Alamofire向服务器发送数据。我有一个图像,我想上传到服务器的数据形式与一些其他参数。在Alamofire中,我使用multipartFormData方法发布所有参数和图像。服务器需要数据为JSON格式,参数如下所示: 我正在努力,但它给了我一个失败的回应。以下是我在swift中与alamofire合作的代码: 我的服务器接受BLOB数据中的映像。如果有人能帮我。非常感谢。

  • 我正在用Swift开发一个iPhone应用程序。我正在使用Alamofire框架来处理http请求。我将用于POST,GET等,如下所示: 我使用将图像上载到服务器: 谁能帮我解决这个问题? 谢谢!:)