[MONGODB] 당신은 어떻게 JSON 개체에서 이미지 파일을 배치해야합니까?
MONGODB당신은 어떻게 JSON 개체에서 이미지 파일을 배치해야합니까?
나는 비디오 게임을위한 게임의 이름, 장르 및 이미지 등 각각 포함 된 요소를 데이터베이스를 만드는 중이라서. 그것은 DB에 대한 JSON 객체로 이미지를 넣을 수 있습니까? 그렇지 않으면이 주위에 방법은 무엇입니까?
해결법
-
==============================
1.나는 두 가지 방법으로 그 일을 생각할 수 있습니다 :
나는 두 가지 방법으로 그 일을 생각할 수 있습니다 :
디렉토리 (말의 DIR1)에 파일 시스템에서 파일을 저장하고 (타임 스탬프 일 수 있음) 이름이 모든 파일에 대해 고유한지 어떤 보장하지만 (말의 xyz123.jpg를) 이름을 변경 한 후 일부 데이터베이스에서이 이름을 저장. 그런 다음 JSON을 생성하는 동안이 파일 이름을 끌어와 (http://example.com/dir1/xyz123.png 될 것입니다)와 JSON에 삽입 완전한 URL을 생성합니다.
자료 64 인코딩, 그것은 기본적으로 ASCII 텍스트에 임의의 바이너리 데이터를 인코딩하는 방법입니다. 그것은 잠재적 끝에 패딩의 비트 데이터의 3 바이트 당 4 개 개의 문자를 얻어, 플러스. 본질적으로, 입력의 각 6 비트는 64 개 문자로 인코딩된다. 「표준」은 알파벳과 + 및 A-Z, A-Z, 0-9를 사용 / 패딩 자로 = 가진. URL 안전 변종이있다. 이 방법은 그것을 가져 오는 동안 이미지 및 디코딩 인코딩 저장 동안의 MongoDB를 직접 이미지를 넣을 수 있습니다 그래서, 그것은 자신의 단점 몇 가지가 있습니다 :
출처
A.) 캔버스
, 이미지 객체로 이미지를로드 캔버스에 페인트와 dataURL에 캔버스 백을 변환합니다.
function convertToDataURLviaCanvas(url, callback, outputFormat){ var img = new Image(); img.crossOrigin = 'Anonymous'; img.onload = function(){ var canvas = document.createElement('CANVAS'); var ctx = canvas.getContext('2d'); var dataURL; canvas.height = this.height; canvas.width = this.width; ctx.drawImage(this, 0, 0); dataURL = canvas.toDataURL(outputFormat); callback(dataURL); canvas = null; }; img.src = url; }
용법
convertToDataURLviaCanvas('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL });
지원되는 입력 형식 이미지 / PNG 이미지 / JPEG 화상 / JPG 이미지 / GIF 이미지 / BMP, 이미지 / TIFF 이미지 / X-아이콘, 이미지 / SVG + XML, 이미지 / WebP 형식 이미지 / XXX
B.)을 FileReader
XMLHttpRequest를 통해 BLOB으로 이미지를로드하고 데이터 URL로 변환을 FileReader API를 사용합니다.
function convertFileToBase64viaFileReader(url, callback){ var xhr = new XMLHttpRequest(); xhr.responseType = 'blob'; xhr.onload = function() { var reader = new FileReader(); reader.onloadend = function () { callback(reader.result); } reader.readAsDataURL(xhr.response); }; xhr.open('GET', url); xhr.send(); }
이러한 접근 방식
용법
convertFileToBase64viaFileReader('http://bit.ly/18g0VNp', function(base64Img){ // Base64DataURL });
출처
-
==============================
2.JSON 형식 값의 유형 만 포함 할 수 있습니다 :
JSON 형식 값의 유형 만 포함 할 수 있습니다 :
이미지는 그 중 어느 것도없는 유형 "진"이다. 그래서 직접 JSON에 이미지를 삽입 할 수 없습니다. 당신이 할 수있는 일은 다음 일반 문자열로 사용할 수있는 텍스트 표현으로 이미지를 변환합니다.
그것을 달성하기위한 가장 일반적인 방법은 base64로 불리는 것과입니다. 기본적으로, 대신에 1 및 0으로 인코딩, 그것의 텍스트 표현을 더 컴팩트하게 64 개 문자의 범위를 사용한다. 그래서 예를 들어 이진 숫자 '64'base64로 단순히 하나의 문자있는 동안, 1000000으로 표시됩니다 =.
브라우저 또는하지를 수행하려는 경우에 따라 64 기수의 이미지를 인코딩하는 방법에는 여러 가지가 있습니다.
당신이 웹 애플리케이션을 개발하는 경우, 그것은 다른 곳 JSON 또는 그 이미지에 바이너리 형태로 별도 저장 이미지 저장 경로에 대한 방법이 더욱 효과적 일 것입니다. 그것은 또한 이미지를 캐시 클라이언트의 브라우저를 할 수 있습니다.
-
==============================
3.사용 데이터 URL 방식 : https://en.wikipedia.org/wiki/Data_URI_scheme
사용 데이터 URL 방식 : https://en.wikipedia.org/wiki/Data_URI_scheme
이 경우 HTML에 직접 해당 문자열을 사용합니다
-
==============================
4.몽고 DB에 직접 파일을 업로드하려면 그리드 FS를 사용할 수있다. 특정 객체의 데이터를 호출 할 때 파일 시스템에서 파일의 어느 곳을 업로드 한 후 모든 항목에 대한 JSON 객체에 이미지의 URL을 넣어 당신을 제안합니다하지만 당신은 URL을 사용하여 이미지를 호출 할 수 있습니다.
몽고 DB에 직접 파일을 업로드하려면 그리드 FS를 사용할 수있다. 특정 객체의 데이터를 호출 할 때 파일 시스템에서 파일의 어느 곳을 업로드 한 후 모든 항목에 대한 JSON 객체에 이미지의 URL을 넣어 당신을 제안합니다하지만 당신은 URL을 사용하여 이미지를 호출 할 수 있습니다.
당신이 사용하고있는 백엔드 기술을 말해? 그 기반으로 추가 제안을 제공 할 수 있습니다.
-
==============================
5.
public class UploadToServer extends Activity { TextView messageText; Button uploadButton; int serverResponseCode = 0; ProgressDialog dialog = null; String upLoadServerUri = null; /********** File Path *************/ final String uploadFilePath = "/mnt/sdcard/"; final String uploadFileName = "Quotes.jpg"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_upload_to_server); uploadButton = (Button) findViewById(R.id.uploadButton); messageText = (TextView) findViewById(R.id.messageText); messageText.setText("Uploading file path :- '/mnt/sdcard/" + uploadFileName + "'"); /************* Php script path ****************/ upLoadServerUri = "http://192.1.1.11/hhhh/UploadToServer.php"; uploadButton.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog = ProgressDialog.show(UploadToServer.this, "", "Uploading file...", true); new Thread(new Runnable() { public void run() { runOnUiThread(new Runnable() { public void run() { messageText.setText("uploading started....."); } }); uploadFile(uploadFilePath + "" + uploadFileName); } }).start(); } }); } public int uploadFile(String sourceFileUri) { String fileName = sourceFileUri; HttpURLConnection connection = null; DataOutputStream dos = null; String lineEnd = "\r\n"; String twoHyphens = "--"; String boundary = "*****"; int bytesRead, bytesAvailable, bufferSize; byte[] buffer; int maxBufferSize = 1 * 1024 * 1024; File sourceFile = new File(sourceFileUri); if (!sourceFile.isFile()) { dialog.dismiss(); Log.e("uploadFile", "Source File not exist :" + uploadFilePath + "" + uploadFileName); runOnUiThread(new Runnable() { public void run() { messageText.setText("Source File not exist :" + uploadFilePath + "" + uploadFileName); } }); return 0; } else { try { // open a URL connection to the Servlet FileInputStream fileInputStream = new FileInputStream( sourceFile); URL url = new URL(upLoadServerUri); // Open a HTTP connection to the URL connection = (HttpURLConnection) url.openConnection(); connection.setDoInput(true); // Allow Inputs connection.setDoOutput(true); // Allow Outputs connection.setUseCaches(false); // Don't use a Cached Copy connection.setRequestMethod("POST"); connection.setRequestProperty("Connection", "Keep-Alive"); connection.setRequestProperty("ENCTYPE", "multipart/form-data"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary); connection.setRequestProperty("uploaded_file", fileName); dos = new DataOutputStream(connection.getOutputStream()); dos.writeBytes(twoHyphens + boundary + lineEnd); // dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\"" // + fileName + "\"" + lineEnd); dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename=" + URLEncoder.encode(fileName, "UTF-8") + lineEnd); dos.writeBytes(lineEnd); // create a buffer of maximum size bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); buffer = new byte[bufferSize]; // read file and write it into form... bytesRead = fileInputStream.read(buffer, 0, bufferSize); while (bytesRead > 0) { dos.write(buffer, 0, bufferSize); bytesAvailable = fileInputStream.available(); bufferSize = Math.min(bytesAvailable, maxBufferSize); bytesRead = fileInputStream.read(buffer, 0, bufferSize); } // send multipart form data necesssary after file data... dos.writeBytes(lineEnd); dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); // Responses from the server (code and message) int serverResponseCode = connection.getResponseCode(); String serverResponseMessage = connection.getResponseMessage(); Log.i("uploadFile", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode); if (serverResponseCode == 200) { runOnUiThread(new Runnable() { public void run() { String msg = "File Upload Completed.\n\n See uploaded file here : \n\n" + " http://www.androidexample.com/media/uploads/" + uploadFileName; messageText.setText(msg); Toast.makeText(UploadToServer.this, "File Upload Complete.", Toast.LENGTH_SHORT) .show(); } }); } // close the streams // fileInputStream.close(); dos.flush(); dos.close(); } catch (MalformedURLException ex) { dialog.dismiss(); ex.printStackTrace(); runOnUiThread(new Runnable() { public void run() { messageText .setText("MalformedURLException Exception : check script url."); Toast.makeText(UploadToServer.this, "MalformedURLException", Toast.LENGTH_SHORT) .show(); } }); Log.e("Upload file to server", "error: " + ex.getMessage(), ex); } catch (Exception e) { dialog.dismiss(); e.printStackTrace(); runOnUiThread(new Runnable() { public void run() { messageText.setText("Got Exception : see logcat "); Toast.makeText(UploadToServer.this, "Got Exception : see logcat ", Toast.LENGTH_SHORT).show(); } }); Log.e("Upload file to server Exception", "Exception : " + e.getMessage(), e); } dialog.dismiss(); return serverResponseCode; } // End else block }
PHP 파일
<?php $target_path = "./Upload/"; $target_path = $target_path . basename( $_FILES['uploadedfile']['name']); if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) { echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded"; } else { echo "There was an error uploading the file, please try again!"; } ?>
from https://stackoverflow.com/questions/34485420/how-do-you-put-an-image-file-in-a-json-object by cc-by-sa and MIT license
'MONGODB' 카테고리의 다른 글
[MONGODB] MongoDB를이 - 어떻게 수집 안에 중첩 된 항목에 대한 쿼리하는? (0) | 2019.12.06 |
---|---|
[MONGODB] 임베디드 데이터베이스로 사용할 수 MongoDB를 수 있습니까? (0) | 2019.12.06 |
[MONGODB] 산화 마그네슘 (MgO) 세션을 유지하는 모범 사례 (0) | 2019.12.06 |
[MONGODB] MongoDB의 메모리 사용량을 제한 할 수있는 옵션이 있습니까? (0) | 2019.12.06 |
[MONGODB] 여러 배열 항목에서 찾을 수 MongoDB를 (0) | 2019.12.06 |