- 파일업로드를 위해서 우선 cos.jar 라이브러리 폴더에 넣기!
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ajax파일 업로드시키기</title>
<script src="http://code.jquery.com/jquery-3.7.0.min.js"></script>
</head>
<body>
<h2>ajax를 이용해서 파일업로드하기</h2>
<input type="file" id="upFile" multiple>
<!-- file 타입에는 files 속성이 있다 -->
<!-- files 타입은 리스트타입으로, 넣는 파일들이 담겨있다 -->
<button id="uploadBtn">업로드파일</button>
<script>
$("#uploadBtn").click(e=>{
const form = new FormData();
const fileInput = $("#upFile");
console.log(fileInput);
$.each(fileInput[0].files,(i,f)=>{
form.append("upfile"+i,f);
});
$.ajax({
url:"<%=request.getContextPath()%>/fileUpload",
data:form,
type:"post",
processData:false,
contentType:false,
success:data=>{
alert("업로드가 완료되었습니다.");
},error:(r,m)=>{
alert("업로드 실패했습니다.");
},complete:()=>{
$("#upFile").val('');
}
});
});
</script>
<h2>업로드 이미지 미리보기 기능</h2>
<img src="https://th.bing.com/th/id/OIP.vvmpWt0qBu3LeBgZuUfmGAHaFt?w=223&h=180&c=7&r=0&o=5&pid=1.7"
width="100" height="100" id="profile">
<input type="file" style="display:none" id="profileInput" accept="image/*">
<input type="file" id="upfiles" multiple accept="images/*">
<div id="uploadpreview"></div>
<script>
$("#profile").click(e=>{
$("#profileInput").click();
});
$("#upfiles").change(e=>{
$("#uploadpreview").html('');
const files=e.target.files;
$.each(files,(i,f)=>{
const reader=new FileReader();
reader.onload=e=>{ // 순서 : 3
const img=$("<img>").attr({
src:e.target.result,
"width":"100",
"height":"100"
});
$("#uploadpreview").append(img);
}
reader.readAsDataURL(f); // 순서 : 2
});
});
$("#profileInput").change(e=>{ // 원안에 있는 프로필 이미지 변경
const reader=new FileReader();
reader.onload=e=>{
//e.target.result 속성에 변경된 file이 나옴
$("#profile").attr("src",e.target.result);
}
reader.readAsDataURL(e.target.files[0]);
});
</script>
<style>
#profile{
border-radius:100px;
border:3px solid yellow;
}
</style>
</body>
</html>
package com.ajax.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;
@WebServlet("/fileUpload")
public class AjaxFileUploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AjaxFileUploadServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path=getServletContext().getRealPath("/test");
MultipartRequest mr= new MultipartRequest(request, path, 1024*1024*10,"UTF-8",new DefaultFileRenamePolicy());
String name = mr.getParameter("name");
System.out.println(name);
System.out.println(mr.getFilesystemName("upfile0"));
System.out.println(mr.getOriginalFileName("upfile0"));
List<Map<String,String>> files= new ArrayList();
Enumeration<String> names=mr.getFileNames();
while(names.hasMoreElements()) {
String key=names.nextElement();
System.out.println(key);
System.out.println(mr.getFilesystemName(key));
System.out.println(mr.getOriginalFileName(key));
files.add(Map.of("rename",mr.getFilesystemName(key),"oriname",mr.getOriginalFileName(key)));
}
System.out.println(files);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
- 업로드 되는 위치 -> /test 밑