2014-07-22 3 views
1

현재 브라우저에서 하나의 이미지를 업로드하고 있습니다. 백 엔드에는 Java 코드가 있습니다.이 이미지를 가져 와서 바이트 배열로 변환하고 실제로이 부분을 데이터베이스에 저장하는 중입니다.Java에서 절대 경로를 얻는 방법

코드는 다음과 같이 간다 : 절대적으로 잘 작동 :

String fromLocal = "D:/123.jpg"; 
     File file = new File(fromLocal); 
     InputStream inputStream = null; 
     byte[] bFile= null; 
     byte[] imageData = null; 
     try { 
      inputStream = new BufferedInputStream(new FileInputStream(file)); 
      ByteArrayOutputStream baos = new ByteArrayOutputStream(8192); 
      bFile = new byte[8192]; 
      int count; 
      while((count = inputStream.read(bFile))> 0){ 
       baos.write(bFile, 0, count); 
      } 
      bFile = baos.toByteArray(); 
      if(bFile.length > 0){ 
       imageData = bFile; 
      } 
      baos.flush(); 
      inputStream.close(); 
     } catch (Exception ioe) { 
      //throw ioe; 
     } 

문제는 내가 (/123.jpg 여기 D 같은) 이미지 경로를 하드하려고 할 때마다입니다. 이제 사용자 의존 & 클라이언트 의존 그는 어떤 디렉토리에서 어떤 드라이브 &에서 이미지를로드 할 수 있습니다. 난 서블릿을 사용하는 권한이 없어요. 내 검색어 :

1. D : /123.jpg에서 동일한 이미지를 업로드하려고 시도하는 중 브라우저에서 123.jpg 만 가져 오는 중입니다. D : /123.jpg와 같은 절대 경로가 아닙니다. 때문에 지금은 이미지를 처리 ​​할 수 ​​없습니다.

2. 사용자가 이미지 업로드를 시도한 특정 경로를 알고 싶습니다 (사용자가 C : /images/123.jpg에서 이미지를 업로드 할 수 있음).이 절대 경로를 얻는 방법.

나는 내 세부적인 세부 사항을 내 최선을 다했는데 뭔가 명확하지 않다면 다른 방법으로 설명하려고 노력할 것입니다.

+0

Java에서 getAbsolutePath() 메소드를 찾으십니까 –

+0

사용자가 파일을 어디에서 업로드합니까? 업로드한다는 것은 웹 사이트를 사용하고 있음을 의미하지만 "나는 서블릿을 사용할 권한이 없습니다"라고 말합니다. 소프트웨어는 어디서 실행됩니까? – f1sh

+0

질문 2, 요즘 대부분의 브라우저는 보안상의 이유로 파일의 전체 경로를 게시하지 않을 것이라고 확신합니다. – George

답변

1

사용자가 서블릿에 파일을 업로드하는 경우 해당 파일은 요청 본문에 포함되어 있으며 서버의 경로에는 포함되어 있지 않습니다. 최종 사용자의 클라이언트 컴퓨터의 경로는 관련이 없습니다 (어쨌든 클라이언트 측에서도 액세스 할 수 없습니다).

final Part filePart = request.getPart("file"); 
InputStream filecontent = null; 
: 기본적으로 http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html

(이 예에서) 업로드에 사용되는 필드 이름 file이있는 경우, 당신은 당신의 서블릿에서이 작업을 수행 : 여기에 파일 업로드에 자바 EE 6 tutoral가있다

하고 나중에 try/catch 내 :

filecontent = filePart.getInputStream(); 

... 및 스트림의 데이터를 사용한다.

위의 튜토리얼의 출처는 다음과 같습니다 (나중에 읽을 때 액세스 할 수없는 경우를 대비하여). 이 경우 파일 서버 측에 파일을 씁니다. 물론 귀하의 경우에는 imageData (대신에 DB에 넣음)을 채우게됩니다. 이 때문에 protocol(HTTP)의, 브라우저를 사용하여 양식을 제출하는 경우

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"}) 
@MultipartConfig 
public class FileUploadServlet extends HttpServlet { 

    private final static Logger LOGGER = 
      Logger.getLogger(FileUploadServlet.class.getCanonicalName()); 

    protected void processRequest(HttpServletRequest request, 
      HttpServletResponse response) 
      throws ServletException, IOException { 
     response.setContentType("text/html;charset=UTF-8"); 

     // Create path components to save the file 
     final String path = request.getParameter("destination"); 
     final Part filePart = request.getPart("file"); 
     final String fileName = getFileName(filePart); 

     OutputStream out = null; 
     InputStream filecontent = null; 
     final PrintWriter writer = response.getWriter(); 

     try { 
      out = new FileOutputStream(new File(path + File.separator 
        + fileName)); 
      filecontent = filePart.getInputStream(); 

      int read = 0; 
      final byte[] bytes = new byte[1024]; 

      while ((read = filecontent.read(bytes)) != -1) { 
       out.write(bytes, 0, read); 
      } 
      writer.println("New file " + fileName + " created at " + path); 
      LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
        new Object[]{fileName, path}); 
     } catch (FileNotFoundException fne) { 
      writer.println("You either did not specify a file to upload or are " 
        + "trying to upload a file to a protected or nonexistent " 
        + "location."); 
      writer.println("<br/> ERROR: " + fne.getMessage()); 

      LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
        new Object[]{fne.getMessage()}); 
     } finally { 
      if (out != null) { 
       out.close(); 
      } 
      if (filecontent != null) { 
       filecontent.close(); 
      } 
      if (writer != null) { 
       writer.close(); 
      } 
     } 
    } 

    private String getFileName(final Part part) { 
     final String partHeader = part.getHeader("content-disposition"); 
     LOGGER.log(Level.INFO, "Part Header = {0}", partHeader); 
     for (String content : part.getHeader("content-disposition").split(";")) { 
      if (content.trim().startsWith("filename")) { 
       return content.substring(
         content.indexOf('=') + 1).trim().replace("\"", ""); 
      } 
     } 
     return null; 
    } 
} 
+0

@ Crowder - 서블릿 API 3.0 및 톰캣 7.0을 사용하지 않는 것 같습니다. –

+0

@UdayKonduru : [Apache Commons FileUpload] (http://commons.apache.org/proper/commons-fileupload/) using.html). 근본적으로 : 데이터가 요청에 포함되어 있으므로 요청에서 데이터를 읽습니다. –

1

당신 는 절대 경로를 얻을 수 있습니다.
이미지 파일이 요청 개체 ()에 연결됩니다 (절대 경로가없는 경우). 그게 전부 야 !!!

+0

왜 이것을 downvoted입니까? 맞아! – f1sh

+0

예, 아래 유권자는 의견을 언급 할 수 있습니다 :) – Jaykishan

+0

그것이 맞을 때 제 생각에 유용하게 대답하지 않습니다. @ Jaykishan : downvoters가 논평을 기대하지 마라, 그것은 SE 관리에 의해 활발히 낙심하고있다. :-) (외관상으로는 다만 논쟁 또는 무언가로 이끌어 낸다 ...) –

관련 문제