환경 : maven + springmvc + spring + mybatis + mysql
이 기사는 주로 입력을 사용하여 서버의 지정된 디렉토리에 파일을 업로드하거나 데이터베이스에 저장하는 방법을 설명합니다. 데이터베이스에서 파일을 다운로드하고 이미지 파일을 표시하며 스케일링을 달성하는 방법.
파일을 데이터베이스에 저장하는데, 일반적으로 파일을 저장하는 바이트 배열이며 해당 데이터베이스 데이터 유형은 Blob입니다.
먼저 데이터베이스를 만들어야합니다. 여기에서 MySQL 데이터베이스를 사용합니다.
참고 : 기사에 주어진 코드는 대부분 발췌되어 있으며 완료되지 않았습니다.
1. 준비
Maven을 사용하여 SpringMVC+Spring+MyBatis+MySQL 프로젝트를 만듭니다.
Spring+MyBatis+MySQL을 통합하는 방법은 MyBatis 소개를 참조하고 MyBatis+Spring+MySQL을 구성하십시오.
mybatis 학습 하나, mybatis mybatis + spring + mysql의 소개 및 구성
SpringMVC 환경의 건설은 다음을 참조하십시오. Eclipse를 사용하여 Maven의 SpringMVC 프로젝트를 구축하십시오.
Eclipse를 사용하여 Maven의 SpringMVC 프로젝트를 구축하십시오
전경 HTML에서, 형태의 ENCTYPE는 멀티 파트/형태-데이터이다. 입력 및 select의 이름은 StudentForm의 멤버와 하나씩 해당해야합니다.
업로드 된 URL은 AddAction.do입니다. 이 조치 방법의 매개 변수는 Studentform을 사용하여 제출 된 데이터를 매핑합니다. 현재 제출 된 파일의 데이터를 얻을 수 있습니다. 그런 다음 파일에서 작동합니다.
photo_tbl 테이블 만들기 : photo_data 필드는 파일을 저장하는 데 사용되며 유형은 mybatis longblob입니다. 그런 다음 Mapper의 Java 인터페이스 포토 마이퍼를 작성하십시오. 추가, 삭제, 수정 및 검색 포함; Mappper의 XML 파일 : Java 인터페이스에 해당하는 SQL 문.
그리고 스프링 구성 파일은 Bean 선언을 추가해야합니다.
다음은 HTML, Action 및 StudentForm의 코드 스 니펫입니다. SQL, Photomapper.java 인터페이스 코드 및 Photomapper.xml 파일 코드를 작성하십시오.
1.1 HTML 양식 쓰기 방법
1. <form action = "<c : url value = 'addAction.do'/>"method = "post"encType = "multipart/form-data"> 2. <tl> 4. <td elign = "right"> photo : </td> 5. <td> <input type ""file "name ="StudentPhoto "/6. 9. </form>
1.2 액션 방법
1./** 2. * 추가 - 제출 3. */ 4.@requestMapping (value = "addaction.do") 5.public String add_action (ModelMap Model, StudentForm Form) {6. 7.} 1.3 StudentForm 수업
1. Package liming.student.manager.web.model; 2. 4. 8. Private int StudentSex; 9. 개인 문자열 학생 비틀즈; 10. 개인 멀티 파일 스튜던트 학생. 11. 12.}
1.4 photo_tbl을 만듭니다
1. 테이블을 생성 한 사진 _TBL 2. (3. Photo_ID Varchar (100) 1 차 키, 4. Photo_Data Longblob, 5. File_name Varchar (10) 6.);
1.5 광고기 인터페이스
1.@repository 2.@transactional 3. public interface photomapper {4. 5. public void createphoto (Photoentity Entity); 6. 7. 공개 int deletephotobyphotoid (문자열 사진); 8. 9. public int updatePhotodate (@param ( "photoid") String Photoid, @param ( "photodate") byte [] photodate); 10. 12. 13.} 1.6 Photomapper.xml 파일
첨가, 삭제, 수정 및 검색을 포함하여. 새로 추가 된 Photoid는 MySQL 사용자 정의 기능을 사용하여 기본 키를 자동으로 생성합니다. Blobs를 작동 할 때는 TypeHandler를 "org.apache.ibatis.type.blobtypehandler로 설정해야합니다. 삽입 및 업데이트시 매개 변수는 나중에 지정되어야하며 resultmap에 지정해야합니다.
1. namespace = "liming.student.manager.data.photomapper"> 4. <resultmap type = "lembing.student.manager.data.model.photoentity"id = "photomapper_resultmap_photoentity"> 5. <id property = "photoid" "photo_"javatypy = "jdbctype =" <result property = "photodata"column = "photodata"javatype = "byte []"jdbctype = "blob"typehandler = "org.apache.ibatis.type.blobtypehandler" /> 7. 9. 10. <insert id = "createphoto"parametertype = "liming.student.manager.data.model.photoentity"> 11. <selectkey keyproperty = "photoid"resulttype = "string"order = "> 12. nextVal ( 'photo') 13. file_name) 17. 값 ( #{photoid, jdbctype = varchar}, 18. # #{photodata, javatype = byte [], jdbctype = blob, typehandler = org.apache.ibatis.type.blobtypehandler}, 19. 22. <delete id = "deletephotobyphotoid"> 23. photo_tbl 24에서 삭제. 여기서 photo_id = #{photoid, jdbctype = varchar} 25. </delete> 26. 27. jdbctype = blob, typehandler = org.apache.ibatis.type.blobtypehandler}, 30. file_name = #{filename, jdbctype = varchar} 31. 여기서 photo_id = #{photoid, jdbctype = varchar} 32. id = "getPhotoentityByPhotoid"resultmap = "photomapper_resultmap_photoentity"> 35. photo_id, 36. photo_data, 37. file_name 38. photo_tbl 39에서 photo_id = #{photoid, jdbctype = varchar} 40. </mapper> 41. 1.7 스프링 구성 파일
스프링 구성 파일은 org.springframework.web.multipart.commons.commonsmultipartresolver의 선언을 추가해야합니다.
1. <bean id = "multipartresolver"> 2. <속성 이름 = "maxuploadsize"value = "1073741824" /> 3. < /bean>
2. 파일을 서버에 넣습니다
1. 정적 최종 문자열 uploadfilepath = "d : // temp_upload_file //"; 2. 3./** 4. * 새로 제출 - 제출 파일 만 서버에 저장합니다. 10. String filename = uploadfile.getoriginalfilename (); 11. 입력 스트림은 = uploadFile.getInputStream (); 12. // 서버에 이미 업로드 파일과 동일한 이름이있는 파일이있는 경우 프롬프트 메시지는 출력 13. 파일 tempfile = 새 파일 (uploadfilepath + filename); 14. if (tempfile.exists ()) {15. boolean delresult = tempfile.delete (); 16. System.out.println ( "기존 파일 삭제 :" + delresult); 17.} 18. // 서버에 파일 저장 시작 19. if (! filename.equals ( "")) {20. FileoutputStream fos = new FileOutputStream (uploadFilePath + filename); 21. byte [] buffer = 새로운 바이트 [8192]; // 매번 8K 바이트를 읽습니다. 22. int count = 0; 23. // 업로드 된 파일의 바이트를 읽고 업로드 된 파일 출력 스트림 24. while ((count = is.read (buffer)) {25. fos.write (buffer, 0, count); // 서버 파일에 바이트 스트림을 쓰기 26.} 27. fos.close (); // fileoutputStream 객체를 닫습니다. // inputStream 객체 29.} 30.} catch (filenotfoundException e) {31. e.printstacktrace (); 32.} catch (ioexception e) {33. e.printstacktrace (); 34.} 35.} 3. 파일을 데이터베이스에 업로드하십시오
1./** 2. 7. byte [] windentphotodata = new Byte [(int) form.getstudentPhoto (). getsize ()]; 8. IS.Read (StudentPhotodata); 9. String filename = form.getstudentPhoto (). GetoriginalFilename (); 10. Photenity Photenity = New PhotoEntity (); 11. PhotoEntity.setphotodata (StudentPhotodata); 12. Photowentity.setfilename (filename); 13. this.photomapper.createphoto (photoentity); 14.}
4. 파일을 다운로드하십시오
파일을 다운로드하려면 바이트 배열을 파일로 복원해야합니다.
먼저 MyBatis를 사용하여 데이터베이스에서 바이트 배열을 찾아서 파일 이름 (형식 포함)을 지정하십시오. 그런 다음 outputStream을 사용하여 파일을 입력하십시오
1.@requestMapping (value = "downphotobyId") 2. Public void downphotobystudentid (문자열 ID, 최종 httpservletResponse 응답) {3. photoentity entity = this.photomapper.getPhotoentityByPhotoid (id); 4. byte [] data = entity.getphotodata (); 5. String filename = entity.getFilename () == null? "photo.png": entity.getFilename (); 6. filename = urlencoder.encode (filename, "utf-8"); 7. response.reset (); 8. response.SetHeader ( "내용화", "첨부 파일; filename =/" " + filename +"/""); 9. response.addheader ( "컨텐츠 길이", "" + data.length); 10. response.setContentType ( "Application/Octet-stream; charset = utf-8"); 11. outputStream outputStream = new bufferedOutputStream (response.getOutputStream ()); 12. outputStream.write (데이터); 13. outputStream.flush (); 14. outputStream.close (); 15.}<a href = "< %= request.getContextPath () %>/downphotobyid.do?id=8000001"> 사진 </a>
5. 바이트 이미지 파일 표시
1.@requestMapping (value = "getphotobyid") 2.public void getPhotobyid (문자열 ID, 최종 httpservletResponse 응답) {3. photoentity entity = this.photomapper.getPhotoentityPhotoid (id); 4. byte [] data = entity.getphotodata (); 5. Response.SetContentType ( "image/jpeg"); 6. 응답 .SetchAracterEncoding ( "UTF-8"); 7. outputStream outputsReam = response.getOutputStream (); 8. inputStream in = New ByTearRayInputStream (데이터); 9. int len = 0; 10. byte [] buf = 새로운 바이트 [1024]; 11. while ((len = in.read (buf, 0, 1024))! = -1) {12. outputsReam.write (buf, 0, len); 13.} 14. outputsReam.close (); 15.}<img src = "< %= request.getContextPath () %>/getPhotobyid.do?id=8000001"/>
6. 길이와 너비로 그림을 동일한 비율로 스케일
1.@requestMapping (value = "getPhotoid") 2.public void getPhotobyid (문자열 ID, int 너비, int 높이, 최종 httpservletResponse 응답) {3. photoentity entity = this.photomapper.getPhotoentityByPhotoid (id); 4. byte [] data = entity.getphotodata (); 5. if (너비! = 0 && 높이! = 0) {6. data = scaleimage (데이터, 너비, 높이); 7.} 8. Response.setContentType ( "image/jpeg"); 9. 응답 .SetchAracterEncoding ( "UTF-8"); 10. outputStream outputsReam = response.getOutputStream (); 11. inputStream in = New ByTearRayInputStream (데이터); 12. int len = 0; 13. byte [] buf = 새로운 바이트 [1024]; 14. while ((len = in.read (buf, 0, 1024))! = -1) {15. outputsReam.write (buf, 0, len); 16.} 17. outputsReam.close (); 18.} 19. 20. 공개 정적 바이트 [] scaleimage (byte [] data, int width, int height)는 ioexception {21. bufferedImage buffered_oldimage = imageio.read (new BytearRayinputStream (data)); 22. int imageOldWidth = buffered_oldimage.getWidth (); 23. int imageOldHeight = buffered_oldimage.getheight (); 24. Double scale_x = (이중) 너비 / ImageOldwidth; 25. Double Scale_y = (이중) 높이 / ImageOldHeight; 26. Double scale_xy = math.min (scale_x, scale_y); 27. int imagenewwidth = (int) (imageOldWidth * scale_xy); 28. int imagenewheight = (int) (imageOldHeight * scale_xy); 29. BufferedImage buffered_newimage = new bufferedImage (imageenewwidth, imageNewHeight, bufferedImage.type_int_rgb); 30. Buffered_newimage.getGraphics (). DrawImage (buffered_oldimage.getScaledInstance (imageNewWidth, imageNewHeight, bufferedImage.scale_smooth), 0, 0, null); 31. buffered_newimage.getGraphics (). dispose (); 32. BytearRayoutputStream outputStream = New ByTearRayoutputStream (); 33. imageio.write (buffered_newimage, "jpeg", outputstream); 34. return outputStream.tobytearRay (); 35.}<img src = "< %= request.getContextPath () %>/getPhotobyid.do?id=8000001&width=300&height=300"/>
위는 MyBatis와 SpringMVC의 조합으로 파일 업로드 및 다운로드 기능을 구현합니다. 모든 사람에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 모든 사람에게 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!