ios - 图片从 iOS Swift 上传到 Node.js 和 Express 后端

标签 ios node.js swift image-uploading

我在这里尝试使用 POST 请求上传图像。应用程序后端是 MEAN。当我尝试使用 Postman 时,它正在成功上传。

但是 ios 数据任务显示未定义的文件。

这是我的 MEAN 代码。

var multer  = require('multer')
var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'images/profile_images')
        },
        filename: function (req, file, cb) {

            var getFileExt = function(fileName){
                var fileExt = fileName.split(".");
                if( fileExt.length === 1 || ( fileExt[0] === "" && fileExt.length === 2 ) ) {
                    return "";
                }
                return fileExt.pop();
            }
            cb(null, Date.now() + '.' + getFileExt(file.originalname))
        }
    });

var upload = multer({ storage: storage})
var type = upload.single('profile_pic');

    app.post('/images' ,type ,function(req,res) {
        console.log(req.body, req.file , req);
});

output

file: { fieldname: 'profile_pic', originalname: '1.png', encoding: '7bit', mimetype: 'image/png', destination: 'images/profile_images', filename: '1486012211611.png', path: 'images/profile_images/1486012211611.png', size: 144 }, __onFinished: null }

这是我的 Swift 代码:

@IBAction func uploadImage(_ sender: Any) {
    let api = URL.init(string: "http://localhost:3000/images")
    var request = URLRequest.init(url: api!, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 5)
    request.httpMethod = "POST"

    let boundary = generateBoundaryString()



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


    let imge:Data = UIImageJPEGRepresentation(UIImage.init(named: "image1")!, 1)!;


    let body = NSMutableData()

    let fname = "profile_pic.jpg"
    let mimetype = "image/png"

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8, allowLossyConversion: true)!)
    body.append("Content-Disposition:form-data; name=\"profile_pic\"\r\n\r\n".data(using: String.Encoding.utf8)!)
    body.append("hi\r\n".data(using: String.Encoding.utf8)!)

    body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
    body.append("Content-Disposition:form-data; name=\"profile_pic\"; 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(imge)

    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 = URLSession.shared

    let task = session.dataTask(with: request) { (data, response, error) in
        print(data, response, error!)
    }

    task.resume()

}

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

Output at terminal,

undefined

并且图片没有上传。

你能帮我看看哪里出错了吗?

最佳答案

您正在本地主机上工作。 Alamofire 无法将图像发送到本地主机服务器。

Alamofire with localhost connection problems

关于ios - 图片从 iOS Swift 上传到 Node.js 和 Express 后端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41994735/

相关文章:

ipad - AVURLAsset 拒绝加载视频

ios - 本金和利息的图表

ios - 单个自定义对象的 Swift NSCoding 问题

iphone - 模态 ViewController 消失后,iOS 7 自定义后退按钮消失

node.js - 服务器端 NodeJS - 需要客户端 Windows ID

javascript - Websocket 的正确方法

iphone - IOS 应用程序被拒绝 : 2. 23 - 应用程序必须遵循 iOS 数据存储指南

javascript - phonegap 插件在 CLI 中显示错误

ios - 静态方法中的 UIAlertController 给出错误 : extra argument animated in cell

ios - 如何在我的应用程序中接收共享内容?