загрузка байтов изображения с параметром запроса swift 4 - PullRequest
0 голосов
/ 10 сентября 2018

URL = https://test. .. com / camimage.aspx

Тип метода: Post

Параметр запроса:

  1. Параметр заголовка [«ID пользователя»]
  2. байт изображения

Я получил только вышеуказанную информацию с URL и пост-запросом в многочастных данных. Я попытался с swift4 multipart, но не смог достичь ожидаемого результата.

Обновленный вопрос с кодом и журналом

 func UploadRequest()
{
    let url = URL(string: "https://...com/webcam/camimage.aspx")

    let request = NSMutableURLRequest(url: url!)
    request.httpMethod = "POST"


    let boundary = generateBoundaryString()

    request.addValue("UserID", forHTTPHeaderField: "110159")
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    if (imageView.image == nil)
    {
        return
    }

    let image_data = UIImagePNGRepresentation(imageView.image!)

    if(image_data == nil)
    {
        return
    }

    let body = NSMutableData()
    let fname = "test.png"
    let mimetype = "image/png"


    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition:form-data; name=\"uploaded_file\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append(image_data!)
    body.append("\r\n".data(using: String.Encoding.utf8)!)

    body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)

    request.httpBody = body as Data

    let session = URLSession.shared

    let task = session.dataTask(with: request as URLRequest, completionHandler: {
        (
        data, response, error) in

        guard ((data) != nil), let _:URLResponse = response, error == nil else {
            print("error")
            return
        }

        if let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
        {
            print(dataString)
        }

    })

    task.resume()

}


func generateBoundaryString() -> String
{
    return "*****"
}

Я также добавляю код Android. Это может помочь анализу

            FileInputStream fileInputStream = new FileInputStream(selectedFile);
            URL url = new URL(SERVER_URL);
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoInput(true);//Allow Inputs
            connection.setDoOutput(true);//Allow Outputs
            connection.setUseCaches(false);//Don't use a cached Copy
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
            connection.setRequestProperty("uploaded_file",selectedFilePath);
            connection.setRequestProperty("UserID", "110159");
            //creating new dataoutputstream
            dataOutputStream = new DataOutputStream(connection.getOutputStream());

            //writing bytes to data outputstream
            dataOutputStream.writeBytes(twoHyphens + boundary + lineEnd);
            dataOutputStream.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                    + selectedFilePath + "\"" + lineEnd);

            dataOutputStream.writeBytes(lineEnd);

            //returns no. of bytes present in fileInputStream
            bytesAvailable = fileInputStream.available();
            //selecting the buffer size as minimum of available bytes or 1 MB
            bufferSize = Math.min(bytesAvailable,maxBufferSize);
            //setting the buffer as byte array of size of bufferSize
            buffer = new byte[bufferSize];

            //reads bytes from FileInputStream(from 0th index of buffer to buffersize)
            bytesRead = fileInputStream.read(buffer,0,bufferSize);

            //loop repeats till bytesRead = -1, i.e., no bytes are left to read
            while (bytesRead > 0){
                //write the bytes read from inputstream
                dataOutputStream.write(buffer,0,bufferSize);
                bytesAvailable = fileInputStream.available();
                bufferSize = Math.min(bytesAvailable,maxBufferSize);
                bytesRead = fileInputStream.read(buffer,0,bufferSize);
            }

            dataOutputStream.writeBytes(lineEnd);
            dataOutputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

            serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

            Log.i(TAG, "Server Response is: " + serverResponseMessage + ": " + serverResponseCode);

            //response code of 200 indicates the server status OK
            if(serverResponseCode == 200){
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + "http://coderefer.com/extras/uploads/"+ fileName);
                    }
                });
            }

            //closing the input and output streams
            fileInputStream.close();
            dataOutputStream.flush();
            dataOutputStream.close();

Я могу загрузить изображение через почтальона. До сих пор не удалось настроить для загрузки через код swift.

Пожалуйста, проверьте прикрепленные скриншоты двух инструментов WebMap Chrome. Надеюсь, эксперт может помочь мне ..

первый enter image description here

второй enter image description here

Спасибо заранее.

1 Ответ

0 голосов
/ 10 сентября 2018

используйте этот модуль: https://github.com/Alamofire/Alamofire
Ссылка: https://gist.github.com/DejanEnspyra/5bae2a301b2b2bb5de3109344345617f

func requestWith(endUrl: String, imageData: Data?, parameters: [String : Any], onCompletion: ((JSON?) -> Void)? = nil, onError: ((Error?) -> Void)? = nil){

let url = "http://google.com" /* your API url */

let headers: HTTPHeaders = [
    /* "Authorization": "your_access_token",  in case you need authorization header */
    "Content-type": "multipart/form-data"
]

Alamofire.upload(multipartFormData: { (multipartFormData) in
    for (key, value) in parameters {
        multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
    }

    if let data = imageData{
        multipartFormData.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
    }

}, usingThreshold: UInt64.init(), to: url, method: .post, headers: headers) { (result) in
    switch result{
    case .success(let upload, _, _):
        upload.responseJSON { response in
            print("Succesfully uploaded")
            if let err = response.error{
                onError?(err)
                return
            }
            onCompletion?(nil)
        }
    case .failure(let error):
        print("Error in upload: \(error.localizedDescription)")
        onError?(error)
    }
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...