如何在swift Alamofire中将图像和数据作为Multipart上传

时间:2017-11-02 07:46:27

标签: swift swift3 alamofire alamofireimage

我是一个机器人,我已经在android中实现了这个我需要将此代码转换为swift现在为我的ios项目,我已经尝试使用Alamofire在ios上传我的数据和图像,我一直在努力,因为一个如果你们能在这里帮助我的那一周。

我的数据看起来像这样

First String- 
   ---------SWPMCF1Le5z\r\nContent-Disposition: form-data; name=\"files\"; filename=\"IMG_20171021_192906.jpg\"\r\nContent-Type: image*\/\/*\r\n\r\n"

"This is my image data in bytes"



Second String  
 ---------SWPMCF1Le5z
        Content-Disposition: form-data; name="json"
        Content-Type: application/json

{"thread":{"title":"hh","site_id":177},"comment":{"shift_id":4,"subject":"hh","message":"gt","entered_at":"2017-11-02 10:52:56","priority":"high","author_id":1621,"entities":[],"fields":[],"files":[],"images":[{"filename":"IMG_20171021_192906.jpg"}],"fileData":[{"data":"\/storage\/6535-3331\/DCIM\/Camera\/IMG_20171021_192906.jpg"}]}}
---------SWPMCF1Le5z--

现在我需要使用Alamofire将其发送到服务器,但我得到了

Error code -1001

其中我不知道。 我尝试了几种方式进入Alamofire就像使用multipart,标准方式然后我尝试了标准的方式快速击中服务器没有运气请你们是否可以帮助我。 我用标准方式在android中做了同样的事情。 这是我的安卓代码,如果你们这些人想出来的。

    InputStream fStream = null;
                try {
                    DataOutputStream out = new DataOutputStream(http.getOutputStream());
                    for (int i = 0; i < body.length(); i++) {
                        String string = body.optString(i);
//Here I am writing the image data into http outputstream
                        if (string.startsWith("[FILE]")) {
                            File file = new File(string.replace("[FILE]", ""));
                            fStream = new FileInputStream(file);
                            int bufferSize = 1024;
                            byte[] buffer = new byte[bufferSize];
                            int length;
                            while ((length = fStream.read(buffer)) != -1) {
                                out.write(buffer, 0, length);
                            }
                            fStream.close();
                        } else {

    //Here I am writing the the first and second string.
                                out.writeBytes(string);
                            }
                        }
                        out.flush();
                        out.close();
                    } catch (ConnectException e) {
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                        return null;
                    }
                    try {
                        if (fStream != null) fStream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

请各位帮助我,让我知道是否需要更多代码。 提前谢谢。

0 个答案:

没有答案