简体   繁体   中英

Image upload from iOS Swift to Node.js and Express backend

Here I'm trying to upload an image using POST request. Application backend is MEAN. When I'm trying with Postman, it is uploading successfully.

But ios datatask showing undefined file.

Here is my MEAN code.

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 }

Here is my Swift code:

@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

and the image is not uploading.

Can you help me where I'm going wrong?

You are working on localhost. Alamofire cannot send image to localhost server.

Alamofire with localhost connection problems

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM