SpringMVC는 MultipartFile을 사용하여 파일 업로드를 수행합니다.

17983 단어 multipartfile업로드
크로스 서버에서 파일을 업로드해야 한다면 로컬 파일을 자원 서버에 업로드하는 것입니다. 비교적 좋은 방법은 ftp를 통해 업로드하는 것입니다.Spring MVC+ftp를 결합하여 업로드합니다.우리는 먼저 스프링MVC를 어떻게 설정하는지 알고 ftp를 설정한 다음에 MultipartFile와 결합하여 파일을 업로드해야 한다.
springMVC 업로드는 몇 가지 관건적인jar 패키지가 필요합니다. spring 및 관련 패키지는 스스로 설정할 수 있습니다. 여기서 관건적인jar 패키지를 설명합니다.
1:spring-web-3.2.9.RELEASE.jar(spring의 관건적인 jar 패키지, 버전은 스스로 선택할 수 있음)
2:commons-io-2.2.jar (프로젝트에서 IO를 처리하는 데 사용되는 도구 클래스 패키지)
프로파일
SpringMVC는 MultipartFile로 파일을 업로드하기 때문에 폼의 파일을 처리하기 위해 MultipartResolver를 설정해야 합니다

<!--   --> 
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 
    <property name="defaultEncoding" value="utf-8" /> 
    <property name="maxUploadSize" value="10485760" /> 
    <property name="maxInMemorySize" value="4096" /> 
    <property name="resolveLazily" value="true" /> 
  </bean> 
속성 세부 정보:
defaultEncoding 구성 요청의 인코딩 형식, 기본값은 iso-8859-1
maxUploadSize 구성 파일의 최대 단위(바이트 단위)
maxInMemorySize는 업로드 파일의 캐시를 바이트 단위로 구성합니다.
resolveLazily 속성 사용은 UploadAction에서 파일 크기 이상을 포착하기 위해 파일 해석을 늦추기 위한 것입니다
페이지 구성
페이지의form에enctype="multipart/form-data"

<form id="" name="" method="post" action="" enctype="multipart/form-data">  
폼 탭에enctype="multipart/form-data"를 설정하여 익명으로 파일을 불러오는 정확한 인코딩을 확보합니다.
는 설정 양식의 MIME 인코딩입니다.기본적으로 이 인코딩 형식은 응용 프로그램/x-www-form-urlencoded로 파일 업로드에 사용할 수 없습니다.multipart/form-data를 사용해야만 파일 데이터를 완전하게 전달하고 아래의 조작을 할 수 있습니다.enctype = "multipart/form-data"는 바이너리 데이터를 업로드하는 것입니다.form에 있는 input의 값은 2진법으로 전달되기 때문에request는 값을 얻지 못합니다.
업로드 제어 클래스 작성
업로드 방법을 작성합니다. 결과가 돌아오지 않았습니다. 페이지를 돌리거나 다른 값을 되돌려야 합니다.void를 String,Map 등의 값으로 바꾸고 결과를 되돌려줍니다.

    /** 
 *   
 * @param request 
 * @return 
 */ 
@ResponseBody 
@RequestMapping(value = "/upload", method = {RequestMethod.GET, RequestMethod.POST}) 
public void upload(HttpServletRequest request) { 
  MultipartHttpServletRequest multipartRequest=(MultipartHttpServletRequest)request; 
  MultipartFile file = multipartRequest.getFile("file");//file input name  
  String basePath = " " 
  try { 
    MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 
      if (resolver.isMultipart(request)) { 
      String fileStoredPath = " "; 
      //  
      String randomName = StringUtil.getRandomFileName(); 
      String uploadFileName = file.getOriginalFilename(); 
      if (StringUtils.isNotBlank(uploadFileName)) { 
        //  
        String suffix = uploadFileName.substring(uploadFileName.indexOf(".")); 
        //  
        String newFileName = randomName + suffix; 
        String savePath = basePath + "/" + newFileName; 
        File saveFile = new File(savePath); 
        File parentFile = saveFile.getParentFile(); 
        if (saveFile.exists()) { 
          saveFile.delete(); 
        } else { 
          if (!parentFile.exists()) { 
            parentFile.mkdirs(); 
          } 
        } 
        //  
        FileUtils.copyInputStreamToFile(file.getInputStream(), saveFile); 
        //  
        FTPClientUtil.upload(saveFile, fileStoredPath); 
      } 
    } 
  } catch (Exception e) { 
    e.printStackTrace(); 
  } 
} 
FTP 클라이언트 업로드 도구

package com.yuanding.common.util; 
 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import java.net.SocketException; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.Properties; 
 
import org.apache.commons.lang.StringUtils; 
import org.apache.commons.net.ftp.FTP; 
import org.apache.commons.net.ftp.FTPClient; 
import org.apache.commons.net.ftp.FTPReply; 
import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
 
/** 
 * FTP  
 */ 
public class FTPClientUtil { 
 
  /** 
   *   
   */ 
  private static final Logger LOGGER = LoggerFactory.getLogger(FTPClientUtil.class); 
 
  /** 
   * FTP server configuration--IP key,value is type of String 
   */ 
  public static final String SERVER_IP = "SERVER_IP"; 
 
  /** 
   * FTP server configuration--Port key,value is type of Integer 
   */ 
  public static final String SERVER_PORT = "SERVER_PORT"; 
 
  /** 
   * FTP server configuration--ANONYMOUS Log in key, value is type of Boolean 
   */ 
  public static final String IS_ANONYMOUS = "IS_ANONYMOUS"; 
 
  /** 
   * user name of anonymous log in 
   */ 
  public static final String ANONYMOUS_USER_NAME = "anonymous"; 
 
  /** 
   * password of anonymous log in 
   */ 
  public static final String ANONYMOUS_PASSWORD = ""; 
 
  /** 
   * FTP server configuration--log in user name, value is type of String 
   */ 
  public static final String USER_NAME = "USER_NAME"; 
 
  /** 
   * FTP server configuration--log in password, value is type of String 
   */ 
  public static final String PASSWORD = "PASSWORD"; 
 
  /** 
   * FTP server configuration--PASV key, value is type of Boolean 
   */ 
  public static final String IS_PASV = "IS_PASV"; 
 
  /** 
   * FTP server configuration--working directory key, value is type of String While logging in, the current directory 
   * is the user's home directory, the workingDirectory must be set based on it. Besides, the workingDirectory must 
   * exist, it can not be created automatically. If not exist, file will be uploaded in the user's home directory. If 
   * not assigned, "/" is used. 
   */ 
  public static final String WORKING_DIRECTORY = "WORKING_DIRECTORY"; 
   
 
  public static Map<String, Object> serverCfg = new HashMap<String, Object>(); 
   
  static Properties prop; 
   
  static{ 
    LOGGER.info(" ftp.properties !"); 
    prop = new Properties(); 
    try { 
      InputStream fps = FTPClientUtil.class.getResourceAsStream("/ftp.properties"); 
      prop.load(fps); 
      fps.close(); 
    } catch (Exception e) { 
      LOGGER.error(" ftp.properties !",e); 
    } 
    serverCfg.put(FTPClientUtil.SERVER_IP, values("SERVER_IP")); 
    serverCfg.put(FTPClientUtil.SERVER_PORT, Integer.parseInt(values("SERVER_PORT"))); 
    serverCfg.put(FTPClientUtil.USER_NAME, values("USER_NAME")); 
    serverCfg.put(FTPClientUtil.PASSWORD, values("PASSWORD")); 
    LOGGER.info(String.valueOf(serverCfg)); 
  } 
 
  /** 
   * Upload a file to FTP server. 
   * 
   * @param serverCfg : FTP server configuration 
   * @param filePathToUpload : path of the file to upload 
   * @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced 
   *      by the file name to upload 
   * @throws IOException 
   * @throws SocketException 
   */ 
  public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredName) 
      throws SocketException, IOException { 
    upload(serverCfg, new File(filePathToUpload), fileStoredName); 
  } 
 
  /** 
   * Upload a file to FTP server. 
   * 
   * @param serverCfg : FTP server configuration 
   * @param fileToUpload : file to upload 
   * @param fileStoredName : the name to give the remote stored file, null, "" and other blank word will be replaced 
   *      by the file name to upload 
   * @throws IOException 
   * @throws SocketException 
   */ 
  public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredName) 
      throws SocketException, IOException { 
    if (!fileToUpload.exists()) { 
      throw new IllegalArgumentException("File to upload does not exists:" + fileToUpload.getAbsolutePath 
 
()); 
    } 
    if (!fileToUpload.isFile()) { 
      throw new IllegalArgumentException("File to upload is not a file:" + fileToUpload.getAbsolutePath()); 
    } 
    if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) { 
      throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration."); 
    } 
    transferFile(true, serverCfg, fileToUpload, fileStoredName, null, null); 
  } 
 
  /** 
   * Download a file from FTP server 
   * 
   * @param serverCfg : FTP server configuration 
   * @param fileNameToDownload : file name to be downloaded 
   * @param fileStoredPath : stored path of the downloaded file in local 
   * @throws SocketException 
   * @throws IOException 
   */ 
  public static final void download(Map<String, Object> serverCfg, String fileNameToDownload, String fileStoredPath) 
      throws SocketException, IOException { 
    if (StringUtils.isBlank(fileNameToDownload)) { 
      throw new IllegalArgumentException("File name to be downloaded can not be blank."); 
    } 
    if (StringUtils.isBlank(fileStoredPath)) { 
      throw new IllegalArgumentException("Stored path of the downloaded file in local can not be blank."); 
    } 
    if (StringUtils.isBlank((String) serverCfg.get(SERVER_IP))) { 
      throw new IllegalArgumentException("SERVER_IP must be contained in the FTP server configuration."); 
    } 
    transferFile(false, serverCfg, null, null, fileNameToDownload, fileStoredPath); 
  } 
 
  private static final void transferFile(boolean isUpload, Map<String, Object> serverCfg, File fileToUpload, 
      String serverFileStoredName, String fileNameToDownload, String localFileStoredPath) throws  
 
SocketException, 
      IOException { 
    String host = (String) serverCfg.get(SERVER_IP); 
    Integer port = (Integer) serverCfg.get(SERVER_PORT); 
    Boolean isAnonymous = (Boolean) serverCfg.get(IS_ANONYMOUS); 
    String username = (String) serverCfg.get(USER_NAME); 
    String password = (String) serverCfg.get(PASSWORD); 
    Boolean isPASV = (Boolean) serverCfg.get(IS_PASV); 
    String workingDirectory = (String) serverCfg.get(WORKING_DIRECTORY); 
    FTPClient ftpClient = new FTPClient(); 
    InputStream fileIn = null; 
    OutputStream fileOut = null; 
    try { 
      if (port == null) { 
        LOGGER.debug("Connect to FTP server on " + host + ":" + FTP.DEFAULT_PORT); 
        ftpClient.connect(host); 
      } else { 
        LOGGER.debug("Connect to FTP server on " + host + ":" + port); 
        ftpClient.connect(host, port); 
      } 
      int reply = ftpClient.getReplyCode(); 
      if (!FTPReply.isPositiveCompletion(reply)) { 
        LOGGER.error("FTP server refuses connection"); 
        return; 
      } 
 
      if (isAnonymous != null && isAnonymous) { 
        username = ANONYMOUS_USER_NAME; 
        password = ANONYMOUS_PASSWORD; 
      } 
      LOGGER.debug("Log in FTP server with username = " + username + ", password = " + password); 
      if (!ftpClient.login(username, password)) { 
        LOGGER.error("Fail to log in FTP server with username = " + username + ", password = " +  
 
password); 
        ftpClient.logout(); 
        return; 
      } 
 
      // Here we will use the BINARY mode as the transfer file type, 
      // ASCII mode is not supportted. 
      LOGGER.debug("Set type of the file, which is to upload, to BINARY."); 
      ftpClient.setFileType(FTP.BINARY_FILE_TYPE); 
 
      if (isPASV != null && isPASV) { 
        LOGGER.debug("Use the PASV mode to transfer file."); 
        ftpClient.enterLocalPassiveMode(); 
      } else { 
        LOGGER.debug("Use the ACTIVE mode to transfer file."); 
        ftpClient.enterLocalActiveMode(); 
      } 
 
      if (StringUtils.isBlank(workingDirectory)) { 
        workingDirectory = "/"; 
      } 
       
      LOGGER.debug("Change current working directory to " + workingDirectory); 
      changeWorkingDirectory(ftpClient,workingDirectory); 
       
      if (isUpload) { // upload 
        if (StringUtils.isBlank(serverFileStoredName)) { 
          serverFileStoredName = fileToUpload.getName(); 
        } 
        fileIn = new FileInputStream(fileToUpload); 
        LOGGER.debug("Upload file : " + fileToUpload.getAbsolutePath() + " to FTP server with name : " 
            + serverFileStoredName); 
        if (!ftpClient.storeFile(serverFileStoredName, fileIn)) { 
          LOGGER.error("Fail to upload file, " + ftpClient.getReplyString()); 
        } else { 
          LOGGER.debug("Success to upload file."); 
        } 
      } else { // download 
        // make sure the file directory exists 
        File fileStored = new File(localFileStoredPath); 
        if (!fileStored.getParentFile().exists()) { 
          fileStored.getParentFile().mkdirs(); 
        } 
        fileOut = new FileOutputStream(fileStored); 
        LOGGER.debug("Download file : " + fileNameToDownload + " from FTP server to local : " 
            + localFileStoredPath); 
        if (!ftpClient.retrieveFile(fileNameToDownload, fileOut)) { 
          LOGGER.error("Fail to download file, " + ftpClient.getReplyString()); 
        } else { 
          LOGGER.debug("Success to download file."); 
        } 
      } 
 
      ftpClient.noop(); 
 
      ftpClient.logout(); 
 
    } finally { 
      if (ftpClient.isConnected()) { 
        try { 
          ftpClient.disconnect(); 
        } catch (IOException f) { 
        } 
      } 
      if (fileIn != null) { 
        try { 
          fileIn.close(); 
        } catch (IOException e) { 
        } 
      } 
      if (fileOut != null) { 
        try { 
          fileOut.close(); 
        } catch (IOException e) { 
        } 
      } 
    } 
  } 
   
  private static final boolean changeWorkingDirectory(FTPClient ftpClient, String workingDirectory) throws IOException{ 
    if(!ftpClient.changeWorkingDirectory(workingDirectory)){ 
      String [] paths = workingDirectory.split("/"); 
      for(int i=0 ;i<paths.length ;i++){ 
        if(!"".equals(paths[i])){ 
          if(!ftpClient.changeWorkingDirectory(paths[i])){ 
            ftpClient.makeDirectory(paths[i]); 
            ftpClient.changeWorkingDirectory(paths[i]); 
          } 
        } 
      } 
    } 
    return true; 
  } 
   
  public static final void upload(Map<String, Object> serverCfg, String filePathToUpload, String fileStoredPath, String  
 
fileStoredName) 
      throws SocketException, IOException { 
    upload(serverCfg, new File(filePathToUpload), fileStoredPath, fileStoredName); 
  } 
   
  public static final void upload(Map<String, Object> serverCfg, File fileToUpload, String fileStoredPath, String  
 
fileStoredName) 
      throws SocketException, IOException { 
    if(fileStoredPath!=null && !"".equals(fileStoredPath)){ 
      serverCfg.put(WORKING_DIRECTORY, fileStoredPath); 
    } 
    upload(serverCfg, fileToUpload, fileStoredName); 
  } 
   
  public static final void upload(String filePathToUpload, String fileStoredPath)throws SocketException, IOException { 
    upload(serverCfg, filePathToUpload, fileStoredPath, ""); 
  } 
   
  public static final void upload(File fileToUpload, String fileStoredPath)throws SocketException, IOException { 
    upload(serverCfg, fileToUpload, fileStoredPath, ""); 
  } 
   
 
 
   
  public static String values(String key) { 
    String value = prop.getProperty(key); 
    if (value != null) { 
      return value; 
    } else { 
      return null; 
    } 
  } 
   
} 
ftp.properties

#  
SERVER_IP=192.168.1.1 
 
#  
SERVER_PORT=21 
 
#  
USER_NAME=userftp 
 
#  
#PASSWORD=passwordftp 
이상은 본문의 전체 내용입니다. 여러분의 학습에 도움이 되고 저희를 많이 응원해 주십시오.

좋은 웹페이지 즐겨찾기