我正在使用Swift 4开发iOS应用程序。
我需要从服务器上的应用程序上传图像,以便稍后将其保存到数据库中。我为此寻找解决方案;首先我使用了base64Encoding,将图像转换为String并将其存储在数据库中,然后当我想上传此图像时,我使用base64解码对其进行解码,但是,我得到了一个黑色image。
因此,我尝试使用以下代码在服务器上上传图像:
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
@IBOutlet var image: UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func selectPicture(_ sender: AnyObject) {
let ImagePicker = UIImagePickerController()
ImagePicker.delegate = self
ImagePicker.sourceType = UIImagePickerControllerSourceType.photoLibrary
self.present(ImagePicker, animated: true, completion: nil)
}
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
image.image = info[UIImagePickerControllerOriginalImage] as? UIImage
self.dismiss(animated: true, completion: nil)
}
@IBAction func upload_request(_ sender: AnyObject) {
UploadRequest()
}
func UploadRequest()
{
let url = URL(string: "http://192.168.101.13/upload.php")
let request = NSMutableURLRequest(url: url!)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
if (image.image == nil)
{
return
}
let image_data = UIImagePNGRepresentation(image.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=\"test\"\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=\"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 "Boundary-\(UUID().uuidString)"
}
}
和php代码:
if (move_uploaded_file($_FILES['file']['tmp_name'], "image.png")) {
echo "File uploaded: ".$_FILES["file"]["name"];}
但是我收到了这些警告,图片没有上传到服务器上:
move_uploaded_file(image.png): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/htdocs/upload.php
move_uploaded_file(): Unable to move '/Applications/XAMPP/xamppfiles/temp/phprJ2M6j' to 'image.png' in /Applications/XAMPP/xamppfiles/htdocs/upload.php
如何在服务器上上传图像成功。
答案 0 :(得分:1)
以下代码对我来说适用于自定义图片名称`
func HITtheSERVER(imageData:Data) {
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMdd_HHmmss"
let stringOfDateTimeStamp = formatter.string(from: Date())
// print("Date time stamp String: \(stringOfDateTimeStamp)")
let remoteName = "IMG_\(stringOfDateTimeStamp)"+".png"
let request = NSMutableURLRequest(url: myUrl!)
request.httpMethod = "POST"
let boundary = generateBoundaryString()
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
var body = Data()
let fname = remoteName
let mimetype = "image/png"
body.append("--\(boundary)\r\n".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
body.append("Content-Disposition:form-data; name=\"test\"\r\n\r\n".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
body.append("hi\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
body.append("Content-Disposition:form-data; name=\"myFile\"; filename=\"\(fname)\"\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
body.append(imageData)
body.append("\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
request.setValue(String(body.count), forHTTPHeaderField: "Content-Length")
request.httpBody = body
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error")
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString as Any)
}
task.resume()
}
func generateBoundaryString() -> String
{
return "Boundary-\(NSUUID().uuidString)"
}`
答案 1 :(得分:0)
如果我们有多个dataType(例如Image和String)以及正文。在这种情况下,以下代码会有所帮助。
`
override func viewDidLoad() {
super.viewDidLoad()
let imageData = image.jpegData(compressionQuality: 0.1)
let formatter = DateFormatter()
formatter.dateFormat = "yyyyMMddHHmmss"
let stringOfDateTimeStamp = formatter.string(from: Date())
let devicekey = UIDevice.current.identifierForVendor?.uuidString
// print("Date time stamp String: \(stringOfDateTimeStamp)")
let remoteName = "IMG\(stringOfDateTimeStamp)"+".jpg"
let parameters = [
[
"key": "myFile",
"src": imageData,
"type": "image/png"
],
[
"key": "key",
"value": "7d67b170-199c-4436-ad9d-cd5daf38f905",
"type": "text"
]] as [[String : Any]]
let boundary = "Boundary-\(UUID().uuidString)"
var body = Data()
var error: Error? = nil
for param in parameters {
if param["disabled"] == nil {
let paramName = param["key"]!
body.append("--\(boundary)\r\n".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
body.append("Content-Disposition:form-data; name=\"\(paramName)\"".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
let paramType = param["type"] as! String
if paramType == "text" {
let paramValue = param["value"] as! String
body.append("\r\n\r\n\(paramValue)\r\n".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
} else {
let paramSrc = param["src"] as! Data
let mimiType = param["type"]
body.append("; filename=\"\(remoteName)\"\r\n".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
body.append("Content-Type: \(mimiType!)\r\n\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
body.append(paramSrc)
body.append("\r\n".data(using: String.Encoding.utf8,allowLossyConversion: false)!)
}
}
}
body.append("--\(boundary)--\r\n".data(
using: String.Encoding.utf8,
allowLossyConversion: false)!)
let request = NSMutableURLRequest(url: myUrl!)
request.httpMethod = "POST"
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.setValue(String(body.count), forHTTPHeaderField: "Content-Length")
request.httpBody = body
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest) {
(
data, response, error) in
guard let _:NSData = data as NSData?, let _:URLResponse = response, error == nil else {
print("error\(error!)")
return
}
let dataString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print(dataString as Any)
}
task.resume()
}
func generateBoundaryString() -> String
{
return "Boundary-\(NSUUID().uuidString)"}
`