웹 개발

java file transfer

노루아부지 2019. 12. 27. 15:28

받는 쪽 코드 ( Receiver )

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Objects;

import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wowsoft.docs.commonlogic.abstractclass.AbstractController;

import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;

// @Slf4j 은 log4j (log.debug .. )를 쓰기 위함. 삭제 해도 무방.
// @MultipartConfig 꼭 필요! 매우 중요!!
@Slf4j
@Controller
@RequestMapping("/common/upload")
@MultipartConfig
public class FileTransferController extends AbstractController {

	@RequestMapping("/receiver")
	public @ResponseBody String receiver(HttpServletRequest request, HttpServletResponse response) {
    	// Retrieves <input type="text" name="destination">
		String destination = request.getParameter("destination");
        // Retrieves <input type="text" name="filename">
		String fileName = request.getParameter("filename");
		JSONObject resultObj = new JSONObject();
		boolean success = true;
		String message = null;
		//String fileName = Paths.get(filePart.getSubmittedFileName())
        //					.getFileName().toString(); // MSIE fix.

		InputStream fileContent = null;
		OutputStream outStream = null;

		log.debug("destindation : " + destination);
		log.debug("fileName : " + fileName);

		try {
        	// Retrieves <input type="binaryFile" name="binaryFile">
			Part filePart = request.getPart("binaryFile");
			fileContent = filePart.getInputStream();

			// 아래 주석 부분은 파일을 전송하는 부분에서 filename이 존재한다면 사용 가능.
			// ex) Content-Disposition: form-data; 
            //		name=\"binaryFile\";
            //		filename=\"" + binaryFile.getName() + "\""
			
            // File file = new File("d:\\" + filePart.getSubmittedFileName());
			File file = new File("d:\\" + fileName);

			outStream = new FileOutputStream(file);

			// 읽어들일 버퍼크기를 메모리에 생성
			byte[] buf = new byte[1024];

			int len = 0;

			// 끝까지 읽어들이면서 File 객체에 내용들을 쓴다
			while ((len = fileContent.read(buf)) > 0){

				outStream.write(buf, 0, len);

			}
			// Stream 객체를 모두 닫는다.
		}
		catch(Exception e) {
			e.printStackTrace();
			message = e.getMessage();
			success = false;
		}
		finally {
			try {
				if(outStream != null) outStream.close();
				if(fileContent != null) fileContent.close();
			} catch (IOException e) {
			}
		}

		resultObj.put("result", success);
		resultObj.put("msg", Objects.toString(message, ""));

		return resultObj.toString();
	}
}

 

보내는 쪽 코드 ( Sender )

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;

public class Sender {
	public static void main(String [] args) throws IOException {
		String url = "http://localhost:8080/common/upload/receiver";
		String charset = "UTF-8";
		// File textFile = new File("/path/to/file.txt");
		File binaryFile = new File("C:\\test.txt");
        // Just generate some unique random value.
		String boundary = Long.toHexString(System.currentTimeMillis());
		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.
			// 여러개의 Content-Disposition 동시 전송 가능.
			writer.append("--" + boundary).append(CRLF);
			writer.append("Content-Disposition: form-data; name=\"filename\"").append(CRLF);
			writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
			writer.append(CRLF).append(binaryFile.getName()).append(CRLF).flush();

			writer.append("--" + boundary).append(CRLF);
			writer.append("Content-Disposition: form-data; name=\"destination\"").append(CRLF);
			writer.append("Content-Type: text/plain; charset=" + charset).append(CRLF);
			writer.append(CRLF).append("out").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);
			// filename 파라메터는 꼭 있어야 함.
			// 없으면 receiver에서 filePart.getSubmittedFileName()이 null임
			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();

			// Request is lazily fired whenever you need to obtain information about response.
			int responseCode = ((HttpURLConnection) connection).getResponseCode();
			StringBuffer sbResponse = new StringBuffer();

			// get response
			if(200 == responseCode) {
				// success
				BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

				String line = null;

				while ((line = br.readLine()) != null) {
					sbResponse.append(line);
				}
			}
			else {
				// fail
				sbResponse.append(((HttpURLConnection) connection).getResponseMessage());
			}

			System.out.println(responseCode); // Should be 200
			System.out.println(sbResponse.toString());
		}
		catch(Exception e) {
			e.printStackTrace();
		}
	}
}

 

 

[참고 사이트]

https://stackoverflow.com/questions/2422468/how-to-upload-files-to-server-using-jsp-servlet/2424824#2424824

 

How to upload files to server using JSP/Servlet?

How can I upload files to server using JSP/Servlet? I tried this:

stackoverflow.com

 

https://stackoverflow.com/questions/2793150/how-to-use-java-net-urlconnection-to-fire-and-handle-http-requests

 

How to use java.net.URLConnection to fire and handle HTTP requests?

Use of java.net.URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it. That tutorial basically only shows how to fire a GET request and read the response...

stackoverflow.com

728x90

'웹 개발' 카테고리의 다른 글

파일 업로드 취약점 (webshell upload)  (0) 2020.01.30
[java] https connection  (0) 2019.12.30
REST API 호출 예제  (0) 2019.12.23
java에서 logback 사용  (0) 2019.12.16
JSP / JSTL 에서 URL encode 하는 방법  (0) 2019.11.21
loading