2016-10-10 2 views
1

HTML 파일 입력 중 바이트 [] 내용 방법 :자바 서블릿 - 나는 형태로 다음과 같은 입력이있는 JSP 페이지했습니다

<input type="file" name="image" id="image" accept="image/*">

그리고 제출 실행 버튼 ().

제출 된 정보는 Servlet에 의해 처리됩니다. "image"매개 변수에서 바이트 (바이트 배열 - 바이트 [])를 가져와야합니다.

가능합니까? 나는 그것을 찾고 있었지만 그것을 찾을 수 없었습니다. reddit.com/r/javahelp에/U/jmeisner707에 의해

해결 방법 : 폼에 enctype="multipart/form-data"를 서블릿에 다음 코드 쓰기 :

태그를 추가

Part part = request.getPart("image"); InputStream = part.getInputStream();

후를 바이트 배열을 입력 스트림에서 가져올 수 있어야하므로 서블릿에 다음 주석을 추가해야합니다.

`@MultipartConfig

,210
@WebServlet(
    name = "Servlet", 
    urlPatterns = { "/url"}, 
    loadOnStartup = 1 

)는`

는 귀하의 답변 주셔서 감사합니다.

+0

"매개 변수"란 무엇을 의미합니까? 서블릿에서 수신 한 이미지 파일의 바이트에서 바이트 배열을 가져오고 싶습니까? – Dave0504

답변

0

두 부분으로 나누어 파일을 가져온 다음 파일에서 바이트 배열을 가져옵니다.

파일을 가져 오는 방법은이 자습서를 참조하십시오.

Fie upload to Sevlets

그런 다음 IO 바이트 스트림에 대한 오라클 사이트에서이 흔적을 봐주세요. 두 가지를 모두 다 경험했으면 해결할 수 있어야합니다.

Basic I/O


UPDATE이 응답에 대한 의견과 관련

, FileInputStream에 서버에서 파일을 사용하여 작업 구현이 튜토리얼의 약간 수정 된 버전을 사용하여 아래에 주어진다 . 가장 좋은 방법은 아니지만 작동합니다.

package cmpdhoug; 

import java.io.*; 
import java.util.*; 

import javax.servlet.ServletConfig; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.MultipartConfig; 
import javax.servlet.annotation.WebServlet; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.io.output.*; 


@WebServlet (
     name = "UploadServlet", 
     urlPatterns = "/UploadServlet", 
     loadOnStartup = 1 
) 
public class UploadServlet extends HttpServlet { 

    private boolean isMultipart; 
    private String filePath, tempPath; 
    private int maxFileSize = 5242880; 
    private int maxMemSize = 5 * 1024; 
    private File file ; 

    public void init(){ 
     // Get the file location where it would be stored. 
     filePath = 
       getServletContext().getInitParameter("file-upload"); 
     tempPath = getServletContext().getInitParameter("temp-upload"); 
    } 
    public void doPost(HttpServletRequest request, 
         HttpServletResponse response) 
      throws ServletException, java.io.IOException { 
     // Check that we have a file upload request 
     isMultipart = ServletFileUpload.isMultipartContent(request); 
     response.setContentType("text/html"); 
     java.io.PrintWriter out = response.getWriter(); 
     if(!isMultipart){ 
      out.println("<html>"); 
      out.println("<head>"); 
      out.println("<title>Servlet upload</title>"); 
      out.println("</head>"); 
      out.println("<body>"); 
      out.println("<p>No file uploaded</p>"); 
      out.println("</body>"); 
      out.println("</html>"); 
      return; 
     } 
     DiskFileItemFactory factory = new DiskFileItemFactory(); 
     // maximum size that will be stored in memory 
     factory.setSizeThreshold(maxMemSize); 
     // Location to save data that is larger than maxMemSize. 
     factory.setRepository(new File(tempPath)); 

     // Create a new file upload handler 
     ServletFileUpload upload = new ServletFileUpload(factory); 
     // maximum file size to be uploaded. 
     upload.setSizeMax(maxFileSize); 

     try{ 
      // Parse the request to get file items. 
      List fileItems = upload.parseRequest(request); 

      // Process the uploaded file items 
      Iterator i = fileItems.iterator(); 

      out.println("<html>"); 
      out.println("<head>"); 
      out.println("<title>Servlet upload</title>"); 
      out.println("</head>"); 
      out.println("<body>"); 
      while (i.hasNext()) 
      { 
       FileItem fi = (FileItem)i.next(); 
       if (!fi.isFormField()) 
       { 
        // Get the uploaded file parameters 
        String fieldName = fi.getFieldName(); 
        String fileName = fi.getName(); 
        String contentType = fi.getContentType(); 
        boolean isInMemory = fi.isInMemory(); 
        long sizeInBytes = fi.getSize(); 
        // Write the file 
        if(fileName.lastIndexOf("\\") >= 0){ 
         file = new File(filePath + 
           fileName.substring(fileName.lastIndexOf("\\"))) ; 
        }else{ 
         file = new File(filePath + 
           fileName.substring(fileName.lastIndexOf("\\")+1)) ; 
        } 
        fi.write(file) ; 
        out.println("Uploaded Filename: " + fileName + "<br>"); 
       } 
      } 


      // Get byte stream from file uploaded to server. 
      FileInputStream fis = new FileInputStream(file); 
      byte[] byteArray = new byte[(int) file.length()]; 

      // Add the bytes from the file to the array 
      for(int j = 0; j < byteArray.length; j++){ 
       byteArray[j] = (byte)fis.read(); 
       // Just to show the bytes are in the array. 
       System.out.println(byteArray[j]); 
      } 
      fis.close(); 
      out.println("</body>"); 
      out.println("</html>"); 
     }catch(Exception ex) { 
      System.out.println(ex); 
     } 


    } 
    public void doGet(HttpServletRequest request, 
         HttpServletResponse response) 
      throws ServletException, java.io.IOException { 

     throw new ServletException("GET method used with " + 
       getClass().getName()+": POST method required."); 
    } 
} 

당신은 또한 당신의 서버가 Tomcat 설치 파일이 로컬에있는 곳과 다를 수 있습니다 귀하의 응용 프로그램을 배포 어디든지 올바른 파일 경로를 제공하기 위해 web.xml 파일을 업데이트하는 것이 있는지 확인해야합니다.

web.xml을

<!DOCTYPE web-app PUBLIC 
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" 
"http://java.sun.com/dtd/web-app_2_3.dtd" > 



<web-app> 
    <display-name>Archetype Created Web Application</display-name> 

    <context-param> 
    <param-name>file-upload</param-name> 
    <param-value>/Users/dave/Library/Caches/IntelliJIdea2016.2/tomcat/webapps/data/</param-value> 
    </context-param> 
    <context-param> 
     <param-name>temp-upload</param-name> 
     <param-value>/Users/dave/Library/Caches/IntelliJIdea2016.2/tomcat/webapps/temp/</param-value> 
    </context-param> 
</web-app> 

치어 (당신이 webapps/datawebapps/temp 폴더를 만들 수 있는지 확인) 예를 들어 내 Tomcat 설치는 /dave/servers/Tomcat/에 있지만 내 서버는 아래의 PARAMS에 배포합니다.종속성이있는 XML

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 
    <modelVersion>4.0.0</modelVersion> 
    <groupId>UploadServlet</groupId> 
    <artifactId>UploadServlet</artifactId> 
    <packaging>war</packaging> 
    <version>1.0-SNAPSHOT</version> 
    <name>UploadServlet Maven Webapp</name> 
    <url>http://maven.apache.org</url> 
    <dependencies> 
    <dependency> 
     <groupId>junit</groupId> 
     <artifactId>junit</artifactId> 
     <version>3.8.1</version> 
     <scope>test</scope> 
    </dependency> 
    <dependency> 
     <groupId>javax.servlet</groupId> 
     <artifactId>javax.servlet-api</artifactId> 
     <version>3.1.0</version> 
     <scope>provided</scope> 
    </dependency> 
    <dependency> 
     <groupId>commons-fileupload</groupId> 
     <artifactId>commons-fileupload</artifactId> 
     <version>1.3.2</version> 
    </dependency> 
    <dependency> 
     <groupId>org.apache.commons</groupId> 
     <artifactId>commons-io</artifactId> 
     <version>1.3.2</version> 
    </dependency> 
    </dependencies> 
    <build> 
    <finalName>UploadServlet</finalName> 
    </build> 

인덱스 파일

<html> 
<head> 
    <title>File Uploading Form</title> 
</head> 
<body> 
<h3>File Upload:</h3> 
Select a file to upload: <br /> 
<form action="UploadServlet" method="post" 
     enctype="multipart/form-data"> 
    <input type="file" name="file" size="50" /> 
    <br /> 
    <input type="submit" value="Upload File" /> 
</form> 
</body> 
</html> 
+0

답장을 보내 주셔서 감사합니다. 첫 번째 링크에서 자습서를 읽었지만 전혀 이해할 수 없었습니다. 지금까지 나는 시도했다 : 'Part filePart = request.getParameter ("image"); InputStream is = filePart.getInputStream();' 그리고 나서 InputStream에서 바이트를 가져 왔지만 filePart는 null입니다./ – BrunoSG

+0

먼저 FileInputStream을 InputStream 대신에 보았습니다. read (byte [] b) 바이트를 배열로 가져 오기. 또한 유일한 인수로 File 유형의 객체를 사용하는 생성자가 있습니다. – Dave0504

+0

@ Dave0504'InputStream'은 동일한 메소드를 가지고 있으며, 열 파일을 입력해야만'FileInputStream'을 사용할 수 있습니다. 여기에있는 데이터는 소켓에서 나옵니다. 'FileInputStream'과 같이 'File' 유형의 객체를 사용하는 생성자는 쓸모가 없습니다. 또한 무의미하다. – EJP

1

것은 내가 바이트를 얻을 필요가있다 (A 바이트 배열 - 바이트 [])은 "이미지"매개 변수 중.

아니요. 요청 입력 스트림을 얻은 다음 표준 Java 사본 루프를 통해 이동해야하는 모든 위치에서 바이트를 복사합니다.

+0

문제는 입력 스트림 ("name"이라는 문자열)에 다른 매개 변수가 저장되어 있다고 생각합니다. 여전히 입력 스트림을 받아야합니까? – BrunoSG

관련 문제