我尝试使用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);
});
输出
file:{fieldname:' profile_pic', originalname:' 1.png', 编码:' 7bit', mimetype:' image / png', 目的地:' images / profile_images', filename:' 1486012211611.png', 路径:' 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)"
}
终端输出
未定义
且图片无法上传。
你能在我出错的地方帮助我吗?
答案 0 :(得分:0)
您正在使用localhost。 Alamofire无法将图像发送到本地服务器。