2016-07-02 4 views
-1

JSP를 사용하여 파일을 업로드하려고하는데 오류가 발생하고 파일이 업로드되지 않습니다.FileUpload가 JSP에서 작동하지 않습니다.

업로드를 위해 사용하고있는 서블릿 코드.

import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.PrintWriter; 
import java.nio.file.Files; 
import java.nio.file.Paths; 
import java.util.*; 
import javax.servlet.ServletContext; 
import javax.servlet.ServletException; 
import javax.servlet.annotation.*; 
import javax.servlet.http.*; 
import org.apache.tomcat.util.http.fileupload.FileItem; 
import org.apache.tomcat.util.http.fileupload.FileUploadException; 
import org.apache.tomcat.util.http.fileupload.RequestContext; 
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; 
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; 
import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; 

/** 
* 
* @author Hemal 
*/ 
@MultipartConfig 
public class UploadServlet extends HttpServlet { 

    private static final long serialVersionUID = 1L; 

    private static final String DATA_DIRECTORY = "data"; 
    private static final int MAX_MEMORY_SIZE = 1024 * 1024 * 2; 
    private static final int MAX_REQUEST_SIZE = 1024 * 1024; 

    @Override 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 

     File file; 
     int maxFileSize = 5000 * 1024; 
     int maxMemSize = 5000 * 1024; 
     ServletContext context = request.getServletContext(); 
     String filePath = context.getInitParameter("file-upload"); 
     PrintWriter out=response.getWriter(); 
     // Verify the content type 
     String contentType = request.getContentType(); 
     if ((contentType.contains("multipart/form-data"))) { 

      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("data")); 

      // 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);//ERROR ON THIS LINE 

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


       while (i.hasNext()) { 
        FileItem fi = (FileItem) i.next(); 
        if (!fi.isFormField()) { 
         // Get the uploaded file parameters 
         String fieldName = fi.getFieldName(); 
         String fileName = fi.getName(); 
         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: " + filePath 
           + fileName + "<br>"); 
        } 
       } 

       } catch (Exception ex) { 
       System.out.println(ex); 
      } 
     } 
    } 
} 

오류가 나는 줄에 수신하고

`List fileItems = upload.parseRequest(request);` 

나는 많은 옵션을 시도했지만 성공하지 못했습니다 HttpServletRequest cannot be converted to RequestContext

입니다.

감사합니다.

편집 JSP에서 파일 업로드와

다른 링크는 사용자 정의 디렉토리에 실제 파일을 저장하지 않고 코드의 일부를 보여줍니다. 디렉토리에 파일을 저장하는 코드가 필요합니다. 그래서 저는 이것이 중복 질문이 아니라고 생각합니다.

+0

오류 메시지를 표시해야합니다. – Elvermg

+0

[Apache Tomcat 7.0.40.0을 사용하는 동안 서블릿에서 파일 업로드 오류가 발생할 수 있습니다] (http://stackoverflow.com/questions/16768086/file-upload-error-in-servlet-while-using-apache-tomcat-7) -0-40-0) 또는 http://stackoverflow.com/questions/17590108/jsp-upload-file-failed – Taha

+0

@Elvermg 질문 자체에 이미 오류 메시지가 표시되었습니다. – Hemal

답변

0

이를 사용할 수 있습니다

InputStream content = uploadedFile.getInputStream(); 
byte[] fileArray = new byte[chooseTheSize]; //Here you must use a size big enough. 
content.read(fileArray); 

// fileArray이 파일입니다.

관련 문제