ajax으로 file upload를 해보자 & 첨부파일 이미지 미리보기
프로그래밍 정리/Front
2020. 3. 9. 14:35
반응형
1. form을 사용하지않고 따로 ajax으로 upload를 해보자
2. 첨부파일 이미지 미리보기
form.jsp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 | <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script> </head> <body> <div> <label for="file1">파일</label> <input type="file" id="file1" name="file1"> <button id="btn_submit" onclick="javascript:fn_submit()">전송</button> </div> <div> <div class="img_wrap"> <img id="img" /> </div> </div> <script type="text/javascript"> //이미지 미리보기 var sel_file; $(document).ready(function() { $("#file1").on("change", handleImgFileSelect); }); function handleImgFileSelect(e) { var files = e.target.files; var filesArr = Array.prototype.slice.call(files); var reg = /(.*?)\/(jpg|jpeg|png|bmp)$/; filesArr.forEach(function(f) { if (!f.type.match(reg)) { alert("확장자는 이미지 확장자만 가능합니다."); return; } sel_file = f; var reader = new FileReader(); reader.onload = function(e) { $("#img").attr("src", e.target.result); } reader.readAsDataURL(f); }); } </script> <script> //파일 업로드 function fn_submit(){ var form = new FormData(); form.append( "file1", $("#file1")[0].files[0] ); jQuery.ajax({ url : "/myapp/result" , type : "POST" , processData : false , contentType : false , data : form , success:function(response) { alert("성공하였습니다."); console.log(response); } ,error: function (jqXHR) { alert(jqXHR.responseText); } }); } </script> </body> </html> | cs |
controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 | package com.bitcamp.myapp; import java.io.File; import java.util.Calendar; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class UploadForm { private String path="C:\\myfolder\\01_project"; @RequestMapping("/form") public String form() { return "form"; } @RequestMapping("/result") public String result(@RequestParam("file1") MultipartFile multi,HttpServletRequest request,HttpServletResponse response, Model model) { String url = null; try { //String uploadpath = request.getServletContext().getRealPath(path); String uploadpath = path; String originFilename = multi.getOriginalFilename(); String extName = originFilename.substring(originFilename.lastIndexOf("."),originFilename.length()); long size = multi.getSize(); String saveFileName = genSaveFileName(extName); System.out.println("uploadpath : " + uploadpath); System.out.println("originFilename : " + originFilename); System.out.println("extensionName : " + extName); System.out.println("size : " + size); System.out.println("saveFileName : " + saveFileName); if(!multi.isEmpty()) { File file = new File(uploadpath, multi.getOriginalFilename()); multi.transferTo(file); model.addAttribute("filename", multi.getOriginalFilename()); model.addAttribute("uploadPath", file.getAbsolutePath()); return "filelist"; } }catch(Exception e) { System.out.println(e); } return "redirect:form"; } // 현재 시간을 기준으로 파일 이름 생성 private String genSaveFileName(String extName) { String fileName = ""; Calendar calendar = Calendar.getInstance(); fileName += calendar.get(Calendar.YEAR); fileName += calendar.get(Calendar.MONTH); fileName += calendar.get(Calendar.DATE); fileName += calendar.get(Calendar.HOUR); fileName += calendar.get(Calendar.MINUTE); fileName += calendar.get(Calendar.SECOND); fileName += calendar.get(Calendar.MILLISECOND); fileName += extName; return fileName; } } | cs |
servlet-context.xml
1 2 3 4 5 6 | <beans:bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <beans:property name="maxUploadSize" value="10000000"></beans:property> //업로드 사이즈 제한 <beans:property name="maxInMemorySize" value="100000"></beans:property> //메모리 최대 사이즈 제한 <beans:property name="uploadTempDir" value="temp"></beans:property> <beans:property name="defaultEncoding" value="utf-8"></beans:property> </beans:bean> | cs |
반응형
'프로그래밍 정리 > Front' 카테고리의 다른 글
jquery - datepicker를 사용하여 날짜 기간 정하기 (0) | 2020.03.27 |
---|---|
ajax을 공통 함수로 만들어서 사용하기 (0) | 2020.03.06 |
jsp내에서 post보내기(가상 폼 만들기) (0) | 2020.03.02 |
html - colgroup (0) | 2020.02.25 |