1. 程式人生 > 實用技巧 >檔案上傳(該教程上傳到本地)

檔案上傳(該教程上傳到本地)

1. Tomcat的server.xml配置檔案中進行配置(注意填寫路徑跟web.xml)之中的路徑是一樣的
`

<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
    maxThreads="150" minSpareThreads="4"/>
-->


<!-- A "Connector" represents an endpoint by which requests are received
     and responses are returned. Documentation at :
     Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
     Java AJP  Connector: /docs/config/ajp.html
     APR (HTTP/AJP) Connector: /docs/apr.html
     Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"  URIEncoding="utf-8"/>
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
           port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
     This connector uses the JSSE configuration, when using APR, the
     connector should be using the OpenSSL style configuration
     described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
           maxThreads="150" scheme="https" secure="true"
           clientAuth="false" sslProtocol="TLS" />
-->

<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />


<!-- An Engine represents the entry point (within Catalina) that processes
     every request.  The Engine implementation for Tomcat stand alone
     analyzes the HTTP headers included with the request, and passes them
     on to the appropriate Host (virtual host).
     Documentation at /docs/config/engine.html -->

<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">

  <!--For clustering, please take a look at documentation at:
      /docs/cluster-howto.html  (simple how to)
      /docs/config/cluster.html (reference documentation) -->
  <!--
  <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
  -->

  <!-- Use the LockOutRealm to prevent attempts to guess user passwords
       via a brute-force attack -->
  <Realm className="org.apache.catalina.realm.LockOutRealm">
    <!-- This Realm uses the UserDatabase configured in the global JNDI
         resources under the key "UserDatabase".  Any edits
         that are performed against this UserDatabase are immediately
         available for use by the Realm.  -->
    <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
           resourceName="UserDatabase"/>
  </Realm>

  <Host name="localhost"  appBase="webapps"
        unpackWARs="true" autoDeploy="true">

    <!-- SingleSignOn valve, share authentication between web applications
         Documentation at: /docs/config/valve.html -->
    <!--
    <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
    -->

    <!-- Access log processes all example.
         Documentation at: /docs/config/valve.html
         Note: The pattern used is equivalent to using pattern="common" -->
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
           prefix="localhost_access_log." suffix=".txt"
           pattern="%h %l %u %t &quot;%r&quot; %s %b" />
<!--<Context path="" docBase="F:\Tomcat 7.0\webapps\zhaowoyou" debug="0"/>-->
	<Context docBase="D:/smbms/upload" path="/imgage" reloadable="false"/>
  </Host>
</Engine>
`

2.開啟你專案的Tomcat執行專案的配置 ,將紅框處的選項勾選(用來解決可能出現的中文亂碼的問題)如果沒有出現中文亂碼就不需要勾選了。

3.匯入檔案上傳的三個jar包
連結:https://pan.baidu.com/s/1NQkAxWmNQSC_1Zquyr6QHA
提取碼:ch2s

4.在表單中新增檔案域

注意新增型別是File的型別
5.在表單的抬頭新增enctype屬性!

6.在介面對應的方法中定義MultipartFile物件接收傳入的檔案

7.在springmvc中配置檔案上傳所需的檢視解析器 注意要加id屬性

` <!--檔案上傳-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
          <!--上傳的最大數量-->
          <property name="maxUploadSize" value="5000000"></property>
          <!--上傳的編碼格式-->
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>`

8.在web.xml中配置檔案上傳後儲存的地址

<!--檔案上傳--> <context-param> <param-name>imagepath</param-name> <param-value>D:/smbms/upload</param-value> </context-param>
9.驗證圖片是否傳入
`/**
* 新增使用者
*
* @return
*/
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public String addUser(HttpServletRequest httpServletRequest, MultipartFile profilePicture) {

    List<String> extNames = new ArrayList<String>();
    extNames.add(".png");
    extNames.add(".jpg");
    extNames.add(".gif");
    //驗證圖片時都是否傳入
    if (profilePicture != null) {
        String oldFileName=profilePicture.getOriginalFilename();
        //獲取檔案字尾名
        String hz=oldFileName.substring(oldFileName.lastIndexOf("."));
        System.out.println(hz);
        if(extNames.contains(hz)){
            //驗證檔案大小
            if(profilePicture.getSize()<=500000000){
                //獲取檔案需要存在伺服器的地址
                String newFilepath=httpServletRequest.getServletContext().getInitParameter("imagepath");
                //設定新檔案的名稱
                String newFileName= UUID.randomUUID().toString()+hz;
                //根據日期進行儲存
                String datePath=new SimpleDateFormat("yyyyMMdd").format(new Date());
                //根據地址和名稱建立檔案物件File
                File file=new File(newFilepath+"/"+datePath+"/"+newFileName);
                if(!file.exists()){
                    file.mkdirs();
                }
                //將檔案內容複製到新檔案中
                try {
                    profilePicture.transferTo(file);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                //配置圖片的虛擬路徑,儲存到user物件
               String realtionPath="/images/"+newFileName;
            }else {
                System.out.println("檔案太大了!");
            }
        }else {
            System.out.println("檔案格式不正確!");
        }
    }

    String userName = httpServletRequest.getParameter("userName");
    String userPassword = httpServletRequest.getParameter("userPassword");
    String userCode = httpServletRequest.getParameter("userCode");
    int gender = Integer.parseInt(httpServletRequest.getParameter("gender"));
    //轉換日期格式
    String briday = httpServletRequest.getParameter("birthday");
    boolean flag = true;
    Date bir = null;
    SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    try {
        // 設定lenient為false. 否則SimpleDateFormat會比較寬鬆地驗證日期,比如2007/02/29會被接受,並轉換成2007/03/01
        format.setLenient(false);
        bir = format.parse(briday);
    } catch (ParseException e) {
        flag = false;
    }

    String phone = httpServletRequest.getParameter("phone");
    String address = httpServletRequest.getParameter("address");
    int userRole = Integer.parseInt(httpServletRequest.getParameter("userRole"));
    User u = new User();
    u.setUserCode(userCode);
    u.setAddress(address);
    u.setUserName(userName);

    if (!flag) {
        u.setBirthday(new Date());
    }
    u.setGender(gender);
    u.setUserRole(userRole);
    u.setUserPassword(userPassword);
    u.setPhone(phone);
    if (userService.addUser(u)) {
        return "redirect:/user/toUserList";
    } else {
        return "useradd";
    }
}`

10.多檔案上傳

11.單檔案上傳的時候可以使用下邊的方式將檔案按時間儲存在本地
//設定新檔案的名稱 String newFileName= UUID.randomUUID().toString()+hz; //根據日期進行儲存 String datePath=new SimpleDateFormat("yyyyMMdd").format(new Date()); //根據地址和名稱建立檔案物件File File file=new File(newFilepath+"/"+datePath+"/"+newFileName);