jsp 파일 업로드 관련

jsp 파일 업로드 관련

작성일 2018.09.10댓글 1건
    게시물 수정 , 삭제는 로그인 필요

졸업 작품을 진행중인 학생입니다ㅜ
제가 파일업로드를 하는데 파일을 선택해서 올리기까지 가능합니다.
근데 다 각자 다른 사진을 선택해도 올라갈 때 파일이 다 똑같은게 올라와요
제가 지정해줄때 c://download에 제목 없음.png 이렇게 지정해 놔서 그런건지
제목 없음.png 이 사진으로만 동일하게 올라가는데 ㅜ 
각각 다 다른 사진들이 올라올 순 없나요ㅜ 코드 첨부할게요 

imageload.jsp 

<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page import="java.io.ByteArrayOutputStream"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>파일 다운로드 페이지</title>
</head>
 
<%

    // a태그의 href로 fileDown1.jsp?file_name="<%=fileName1 을 통해 전달한
    // 중복 방지 처리한 파일명 값을 가져온다.
    String fileName = "제목 없음.png";
     
    // 업로드한 폴더의 위치와 업로드 폴더의 이름을 알아야 한다.
    String savePath = "uploadFile"; // WebContent/uploadFile
    // 위의 폴더는 상대경로이고 절대경로 기준의 진짜 경로를 구해와야한다.
    String sDownPath = "c:\\download";
     
    System.out.println("다운로드 폴더 절대 경로 위치 : " + sDownPath);
    System.out.println("fileName1 : " + fileName);
     
    // 저장되어 있는 폴더경로/저장된 파일명 으로 풀 path를 만들어준다.
        // 자바에서는 \를 표시하기 위해서는 \를 한번 더 붙여주기 때문에 \\로 해준다.
    String sFilePath = sDownPath + "\\" + fileName; // ex)c:\\uploadPath\\image.jpg
    String id = request.getParameter("param1");
    //String filename2 = new String(dFileName.getBytes("8859_1"),"euc-kr");
   // File outputFile = new File(sFilePath);
    File file = new File(sFilePath);
      FileInputStream fis = null;
  
      BufferedInputStream in = null;
      ByteArrayOutputStream bStream = null;
      try{
          fis = new FileInputStream(file);
   in = new BufferedInputStream(fis);
   bStream = new ByteArrayOutputStream();
   int imgByte;
   while ((imgByte = in.read()) != -1) {
      bStream.write(imgByte);
   }

//      response.setHeader("Content-Type", type);
      response.setContentLength(bStream.size());
   
      bStream.writeTo(response.getOutputStream());
      response.getOutputStream().flush();
      response.getOutputStream().close();

      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         if (bStream != null) {
    try {
       bStream.close();
    } catch (Exception est) {
       est.printStackTrace();
    }
      }
         if (in != null) {
    try {in.close();}
           catch (Exception ei) { ei.printStackTrace(); }
  }
  if (fis != null) {
     try {fis.close();}
            catch (Exception efis) { efis.printStackTrace(); }
  }
      }
      
 
%>

imageload2.jsp


<%@page import="java.io.BufferedInputStream"%>
<%@page import="java.io.IOException"%>
<%@page import="java.io.OutputStream"%>
<%@page import="java.io.InputStream"%>
<%@page import="java.net.URLEncoder"%>
<%@page import="java.io.FileInputStream"%>
<%@page import="java.io.File"%>
<%@page import="java.io.ByteArrayOutputStream"%>
<%@page language="java" contentType="image/jpeg; charset=UTF-8" pageEncoding="UTF-8"%>
<%
out.clear();
    // a태그의 href로 fileDown1.jsp?file_name="<%=fileName1 을 통해 전달한
    // 중복 방지 처리한 파일명 값을 가져온다.
    String fileName = "제목 없음.png";
     
    // 업로드한 폴더의 위치와 업로드 폴더의 이름을 알아야 한다.
    String savePath = "uploadFile"; // WebContent/uploadFile
    // 위의 폴더는 상대경로이고 절대경로 기준의 진짜 경로를 구해와야한다.
    String sDownPath = "c:\\download";
     
    System.out.println("다운로드 폴더 절대 경로 위치 : " + sDownPath);
    System.out.println("fileName1 : " + fileName);
     
    // 저장되어 있는 폴더경로/저장된 파일명 으로 풀 path를 만들어준다.
        // 자바에서는 \를 표시하기 위해서는 \를 한번 더 붙여주기 때문에 \\로 해준다.
    String sFilePath = sDownPath + "\\" + fileName; // ex)c:\\uploadPath\\image.jpg
    String id = request.getParameter("param1");
    //String filename2 = new String(dFileName.getBytes("8859_1"),"euc-kr");
   // File outputFile = new File(sFilePath);
    byte [] buffer = new byte[1024];
    ServletOutputStream o = response.getOutputStream();
    try{
    BufferedInputStream in = new BufferedInputStream(new FileInputStream(sFilePath));
    int n = 0;
    while(( n = in.read(buffer, 0, 1024)) != -1)
    {
    o.write(buffer, 0, n);
    }
    o.close();
    in.close();
    }catch(Exception e){
    e.printStackTrace();
    }
%>

writePro.jsp

 <%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="Board.BoardDBBean"
    import="java.sql.Timestamp"
%>
<%@page import="com.oreilly.servlet.multipart.DefaultFileRenamePolicy"%>
<%@page import="com.oreilly.servlet.MultipartRequest"%>
<%@ page import="java.util.*"%>
<%@ page import="java.io.File"%>
<%@ page import="java.io.FileOutputStream"%>

<%-- TODO implements  --%>
<% 
request.setCharacterEncoding("utf-8");
%>
<%-- 글쓰기 폼에 입력한 값을 갖고 BoardDataBean클래스 객체 article를 생성 --%>
<jsp:useBean id="article" scope="page" class="Board.BoardDataBean">
<jsp:setProperty name="article" property="*"/>
</jsp:useBean>

<%
String id = (String)session.getAttribute("id"); // 세션에서 얻어낸 사용자 아이디
//request.getRealPath("상대경로") 를 통해 파일을 저장할 절대 경로를 구해온다.
// 운영체제 및 프로젝트가 위치할 환경에 따라 경로가 다르기 때문에 아래처럼 구해오는게 좋음
String uploadPath = "C:\\download"; //request.getRealPath("/uploadFile");

//out.println("절대경로 : " + uploadPath + "<br/>");
 
int maxSize = 1024 * 1024 * 10; // 한번에 올릴 수 있는 파일 용량 : 10M로 제한
 
String bbs_title = "";
String bbs_pass = "";
String bbs_qna = "";
 
String fileName1 = ""; // 중복처리된 이름
String originalName1 = ""; // 중복 처리전 실제 원본 이름
long fileSize = 0; // 파일 사이즈
String fileType = ""; // 파일 타입
 
MultipartRequest multi = null;
String file1 = "";
try{
    // request,파일저장경로,용량,인코딩타입,중복파일명에 대한 기본 정책
    multi = new MultipartRequest(request,uploadPath,maxSize,"utf-8",new DefaultFileRenamePolicy());
     
    // form내의 input name="name" 인 녀석 value를 가져옴
    bbs_title = multi.getParameter("bbs_title");
    // name="subject" 인 녀석 value를 가져옴
    bbs_pass = multi.getParameter("bbs_pass");
    
    bbs_qna = multi.getParameter("bbs_qna");
     
    // 전송한 전체 파일이름들을 가져옴
    Enumeration files = multi.getFileNames();
    
    while(files.hasMoreElements()){
        // form 태그에서 <input type="file" name="여기에 지정한 이름" />을 가져온다.
        file1 = (String)files.nextElement(); // 파일 input에 지정한 이름을 가져옴
        // 그에 해당하는 실재 파일 이름을 가져옴
        originalName1 = multi.getOriginalFileName(file1);
        // 파일명이 중복될 경우 중복 정책에 의해 뒤에 1,2,3 처럼 붙어 unique하게 파일명을 생성하는데
        // 이때 생성된 이름을 filesystemName이라 하여 그 이름 정보를 가져온다.(중복에 대한 처리)
        fileName1 = multi.getFilesystemName(file1);
        // 파일 타입 정보를 가져옴
        fileType = multi.getContentType(file1);
        // input file name에 해당하는 실재 파일을 가져옴
        File file = multi.getFile(file1);
        // 그 파일 객체의 크기를 알아냄
        fileSize = file.length();
    }
}catch(Exception e){
    e.printStackTrace();
}
// 폼으로 부터 넣어오지 않는 값을 데이터 저장빈 BoardDataBean객체 article 에 직접 저장
article.setWriter(id);
article.setRegDate(new Timestamp(System.currentTimeMillis()));
article.setIp(request.getRemoteAddr());
article.setContent(bbs_qna);
article.setSubject(bbs_title);
article.setPasswd(bbs_pass);
article.setImagePath(uploadPath+"\\" + file1);
//DB 처리빈의 객체를 얻어냄
BoardDBBean dbPro = BoardDBBean.getInstance();
//DB처리빈 BoardDBBean클래스의 insertAricle()메소드를 호출해서 레코드 추가
// 이때 추가될 레코드내용 article를 매개변수로 가짐
//이 메소드의 처리 결과는 check변수에 저장
boolean check = dbPro.insertArticle(article);
//처리겨로가값 check 반환
//out.print(bbs_title);
//out.print(bbs_pass);
//out.print(bbs_qna);
response.sendRedirect("../login/reviewForm.jsp");
%>

제발 도와주세요 ㅜㅡㅜ 


이렇게 같은 사진이 올라와요ㅜㅜ


#jsp 파일 #jsp 파일 업로드 #jsp 파일 열기 #jsp 파일 다운로드 #jsp 파일 실행 #jsp 파일 pdf 변환 #jsp 파일 뷰어 #jsp 파일 위치 #jsp 파일 업로드 db 저장 #jsp 파일 업로드 예제

profile_image 익명 작성일 -

제목없음.png로 고정 시켜서 그런거 같은데요?

JAVA / JSP 파일업로드 관련 의견을...

JAVA / JSP 바탕으로 일을 하게 되었는데 그게 좀 답답해서 지식인 분들의 도움을... 해당 파일업로드하도록 만들어진 프로그램을 설치해야만 그런 기능이 가능할...

jsp 워드 파일 업로드

... jsp 파일 업로드든 다운로드든 방식은 비슷합니다. 딱히 워드만 별도로... 업로드와 다운로드 관련 내용를 답변으로 전부 설명하기는 그래서 잘 정리된 사이트...

JSP질문 파일업로드 관련...

file.jsp ---------------- <%@ page contentType="text/html;charset... 혹시 파일의정보를 가져와서 화면에... 좀 있었으면 하고요 위에부분은 업로드할때...

jsp 파일업로드 관련 궁금증입니다.

예를들어 서버에 1.txt, 2.txt, 3.txt 이런 파일을 넣었습니다. 근데 수정할때 2.txt, 3.txt를 삭제(서버경로에도 완전히 삭제)하고 4.txt파일을 추가하여 1.txt파일과 4.txt만...

jsp 파일 업로드 질문입니다

... apache.jsp.FileInfoView_jsp._jspService... cos.jar를 이용한 파일 업로드 프로그램인데... 혹시..서블릿 관련된,,,,설정파일...