Develop!/php

PHP curl로 파일 전송할 때 mime type 같이 전송하기

체리필터 2016. 5. 23. 17:00
728x90
반응형

필요에 의해 html -> php -> java api로 파일을 전송해야 할 일이 생겼다.

Java Api는 UI에서 바로 사용하면 안되는 상태라서 php를 거쳐 가야 하는데 html에서 올린 파일을 Java API로 전달 하는 과정이 생각보다 쉽지 않아 정리 차원에서 글을 남긴다.

 

Html에서 php로 파일을 올리게 되면 $_FILES 라는 전역변수 안에 정보가 담기고, 실제 파일은 php.ini에서 지정한 임시 디렉토리에 저장된다.

해당 경로는 $_FILES['업로드한 html form name']['tmp_name'] 에 저장되어 있으며, 해당 파일을 다시 Java API 쪽으로 넘겨 주면 된다.

 

넘겨주는 방법은 curl을 사용하면 된다.

다음과 같은 방법으로 하면 된다.

$headers = array("Content-Type:multipart/form-data");
$data = array(
	'Filedata' => '@'.$file['tmp_name'].';filename='.$file['name'].';type='.$file['type']
);

$ch = curl_init();
curl_setopt($ch, CURLOPT_HEADER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_INFILESIZE, $file['size']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $api_url.$uri);

$response = curl_exec($ch);

 

Content-Type을 multipart/form-data로 셋팅하는 부분은 많지만, 많이 찾기 힘들었던 부분은 ".';filename='.$file['name'].';type='.$file['type']" 이다.

html에서 php로 업로드 한 파일은 image/png 인데 php에서 Java로 curl을 통해 업로드 하게 되면, 기본적으로 application/octet-stream 타입으로 업로드 되기 때문이다.

이 부분을 html에서 업로드 한 그대로 by pass 하기 위해서는 위 소스와 같이 값을 지정해 주면 된다.

 

그 후 $response에서 받은 Json 값을 파싱하면 되는데

$response에는 header 정보도 같이 들어오게 되므로 body만 별도로 분리해야 한다.

$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($response, 0, $header_size);
$result = substr($response, $header_size);

 

 

이렇게 하게 되면 header를 제외한 순서 Json body 부분만 받을 수 있게 된다.

728x90
반응형