비전공자 개발일기

Swift Image Upload to Server(PHP) 본문

SWIFT

Swift Image Upload to Server(PHP)

HiroDaegu 2023. 3. 3. 21:33
728x90
SMALL
   func uploadImage(image: UIImage) {
        
        let url = URL(string: "URL/imgUpload.php")!
        
        // 이미지를 JPEG 데이터로 변환
        guard let imageData = image.jpegData(compressionQuality: 0.8) else {
            
            print("Failed to convert image to JPEG data")
            return
            
        }
        
        // URLRequest 생성
        var request = URLRequest(url: url)
        request.httpMethod = "POST"
        
        // HTTP Body에 이미지 데이터 추가
        let boundary = "Boundary-\(UUID().uuidString)"
        request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        let httpBody = NSMutableData()
        httpBody.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
        httpBody.append("Content-Disposition: form-data; name=\"image\"; filename=\"\(selectedImageName)\"\r\n".data(using: String.Encoding.utf8)!)
        httpBody.append("Content-Type: image/\(selectedImageType)\r\n\r\n".data(using: String.Encoding.utf8)!)
        httpBody.append(imageData)
        httpBody.append("\r\n".data(using: String.Encoding.utf8)!)
        httpBody.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
        request.httpBody = httpBody as Data
        
        // URLSession을 사용하여 서버에 요청
        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("ERROR: \(error)")
                return
            }
            guard let response = response as? HTTPURLResponse else {
                print("Invaild response")
                return
            }
            print("Status code: \(response.statusCode)")
            if let data = data, let responseString = String(data: data, encoding: .utf8) {
                print("Response: \(responseString)")
            }
        }
        task.resume()
    }
<?php
	
	// 이미지를 업로드할 디렉토리 경로
	$target_dir = "uploads/";
	// 업로드한 파일의 이름
	$target_file = $target_dir . basename($_FILES["image"]["name"]);
	// 파일을 업로드할 때 발생한 오류
	$error = $_FILES["image"]["error"];

	// 파일 업로드가 정상적으로 처리되었는지 확인합니다.
	if ($error == UPLOAD_ERR_OK) {
		// 파일을 지정된 경로로 이동합니다.
		if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file)) {
			// 업로드된 파일의 경로를 클라이언트에게 전달합니다.
			echo "URL/uploads/$target_file";
		} else {
			echo "Failed to move uploaded file.";
		}
	} else {
		echo "Upload failed with error code $error.";
	}
?>
728x90
LIST

'SWIFT' 카테고리의 다른 글

SafeArea Color Control  (0) 2023.03.06
WKWebView Reload Code  (0) 2023.03.04
UIImagePickerControllerDelegate, UINavigationControllerDelegate  (0) 2023.03.02
WKWebView Phone Call  (0) 2023.03.01
WKWebView Component 1(Alert Event, go Back, go Forward)  (0) 2023.02.27