java檔案上傳功能

來源:互聯網
上載者:User

標籤:java檔案上傳

//jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP ‘index.jsp‘ starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--    <link rel="stylesheet" type="text/css" href="styles.css">    -->
  </head>

  <body>
    <form action="${pageContext.request.contextPath }/Upload3" method="post" enctype="multipart/form-data"> 
      使用者名稱;<input type="text" name="username"/><br/> 
      照 片:<input type="file" name="zhaoPian"/><br/> 
      <input type="submit" value="上傳"/> 
    </form> 
  </body>
</html>





//servlet


package com.kero99.ygc.test;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;import javax.servlet.ServletException;
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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.sun.corba.se.spi.legacy.connection.GetEndPointInfoAgainException;



public class Upload extends HttpServlet{

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

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        //設定響應瀏覽器格式
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String savapath=getServletContext().getRealPath("/WEB-INF/files");
        DiskFileItemFactory diskFileItemFactory=new DiskFileItemFactory();
        ServletFileUpload fileUpload=new ServletFileUpload(diskFileItemFactory);
        try {
            fileUpload.setHeaderEncoding("utf-8");
            List<FileItem> list=fileUpload.parseRequest(request);
            for(FileItem item:list){
                if(item.isFormField()){
                    String name=item.getFieldName();//擷取文本項
                    String value=item.getString("utf-8");//擷取常值內容
                    String value1=new String(name.getBytes("iso8859-1"),"UTF-8");
                }else{//為上傳的是檔案        
                    String filename1=item.getName();
                    String filename=UUID.randomUUID().toString().replace("-","")+filename1;
                    //目錄打散方法 a/b
                    String path=getFileChildPath(filename);        
                    File file=new File(savapath,path);
                    if(!file.exists() && !file.isDirectory()){
                        file.mkdirs();      
                        String extension=FilenameUtils.getExtension(filename);
                        if(!("jsp".equals(extension)||"txt".equals(extension))){
                            File file1=new File(file,filename);
                            item.write(file1);
                            response.getWriter().print("success");
                        }else{
                            response.getWriter().print("檔案不能為jsp和exe類型");
                        }
                    }else{
                        response.getWriter().print("檔案不能是空的");
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //目錄打散
    public String getFileChildPath(String filename){
        int hCode=filename.hashCode();
        String hex=Integer.toHexString(hCode);
        String path=hex.charAt(0)+"/"+hex.charAt(1);
        return path;
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        super.destroy();
    }

    @Override
    public void init() throws ServletException {
        // TODO Auto-generated method stub
        super.init();
    }

}

本文出自 “大道至簡,悟在天成” 部落格,請務必保留此出處http://kero99.blog.51cto.com/12965144/1952200

java檔案上傳功能

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.