자바로 node.js를 사용하는 클라우드 서버에 파일 올리기
조회수 2488회
제목에 다 적어낸것 같지만 현재 개인 프로젝트로 javafx를 사용한 어플리케이션을 만들고 있습니다.
제가 개인적으로 공부하기 위해 Google Cloud Platform을 사용하는데요.
여기에서는 node.js로 프로그래밍을 진행합니다.
위에서 말한 javafx의 앱에서 만든 한 파일(예 : a.exe)을 위의 node.js서버에 올리는 방식은 어떻게 해아하나요..??
아직 많은 경험이 없어서 잘 모르겠지만 java에서는 파일을 보내고 node.js에서는 파일을 받는 코드가 필요하기는 할듯 하지만.. 전혀 모르겠습니다.
받아오는것은 URL로 받으면 된다지만 보내는것은 어렵네요..
1 답변
-
서버에서는 fileupload 패키지를 사용해서 업로드를 받으면 됩니다. https://www.npmjs.com/package/fileupload
자바에서 업로드 하는 코드는 이런 예제가 있네요.
String url = "http://example.com/upload"; String charset = "UTF-8"; String param = "value"; File textFile = new File("/path/to/file.txt"); File binaryFile = new File("/path/to/file.bin"); String boundary = Long.toHexString(System.currentTimeMillis()); // Just generate some unique random value. String CRLF = "\r\n"; // Line separator required by multipart/form-data. URLConnection connection = new URL(url).openConnection(); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); try ( OutputStream output = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, charset), true); ) { // Send normal param. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"param\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); writer.append(CRLF).append(param).append(CRLF).flush(); // Send text file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"textFile\"; filename=\"" + textFile.getName() + "\"").append(CRLF); writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF); // Text file itself must be saved in this charset! writer.append(CRLF).flush(); Files.copy(textFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // Send binary file. writer.append("--" + boundary).append(CRLF); writer.append("Content-Disposition: form-data; name=\"binaryFile\"; filename=\"" + binaryFile.getName() + "\"").append(CRLF); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(binaryFile.getName())).append(CRLF); writer.append("Content-Transfer-Encoding: binary").append(CRLF); writer.append(CRLF).flush(); Files.copy(binaryFile.toPath(), output); output.flush(); // Important before continuing with writer! writer.append(CRLF).flush(); // CRLF is important! It indicates end of boundary. // End of multipart/form-data. writer.append("--" + boundary + "--").append(CRLF).flush(); }
댓글 입력