요즘은 어노테이션, 스프링. 라이브러 없이 파일 전송 처리도 못 하는 사람 많네요.
인서울 컴공과 직원이 신입으로 왔갈래
jdk 만 깔려 있는 컴퓨터에서 클라인트에서 브라우저로 파일하고 input 문자 보냇으니
파일은 저장하고 스트링은 출력해 보라고 했더니 2시간동안 암껏도 못하길래
머하냐고 했더니 스프링 기반에서만 할수 있다고 하길래 경영지원실로 부서 이동 시켯네요.
import javax.servlet.*;
import java.io.*;
import java.util.Collection;
public class FileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private static final String UPLOAD_DIRECTORY = "d";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String boundary = getBoundary(request.getContentType());
if (boundary == null) {
response.getWriter().println("Error: No boundary in request");
return;
}
InputStream inputStream = request.getInputStream();
byte[] buffer = new byte[8192];
int bytesRead;
boolean isFilePart = false;
String fileName = null;
FileOutputStream fileOutputStream = null;
while ((bytesRead = inputStream.read(buffer)) != -1) {
String content = new String(buffer, 0, bytesRead, "ISO-8859-1");
if (content.contains(boundary)) {
if (fileOutputStream != null) {
fileOutputStream.close();
fileOutputStream = null;
isFilePart = false;
}
if (content.contains("Content-Disposition: form-data;")) {
int nameIndex = content.indexOf("name=\"");
if (nameIndex != -1) {
int nameEndIndex = content.indexOf("\"", nameIndex + 6);
String name = content.substring(nameIndex + 6, nameEndIndex);
if (content.contains("filename=\"")) {
int fileNameIndex = content.indexOf("filename=\"");
int fileNameEndIndex = content.indexOf("\"", fileNameIndex + 10);
fileName = content.substring(fileNameIndex + 10, fileNameEndIndex);
isFilePart = true;
} else {
int valueStartIndex = content.indexOf("\r\n\r\n") + 4;
int valueEndIndex = content.indexOf(boundary, valueStartIndex) - 2;
String value = content.substring(valueStartIndex, valueEndIndex);
System.out.println("value);
}
}
}
} else if (isFilePart) {
if (fileOutputStream == null && fileName != null) {
String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
File uploadDir = new File(uploadPath);
if (!uploadDir.exists()) uploadDir.mkdir();
fileOutputStream = new FileOutputStream(new File(uploadDir, fileName));
}
if (fileOutputStream != null) {
fileOutputStream.write(buffer, 0, bytesRead);
}
}
}
if (fileOutputStream != null) {
fileOutputStream.close();
}
response.getWriter().println("File upload and form data processing completed.");
}
private String getBoundary(String contentType) {
if (contentType == null) return null;
String[] params = contentType.split(";");
for (String param : params) {
param = param.trim();
if (param.startsWith("boundary=")) {
return param.substring(9);
}
}
return null;
}
}