1. 程式人生 > >檔案的上傳對錶單的要求

檔案的上傳對錶單的要求

<!-- 
上傳檔案:表單要求
1,enctype="multipart/form-data"
2.表單中需要有type="file"的input
3.表單的請求方式一定是POST。即method="post"
servlet要求
1.不能使用request.getParameter
2.使用request.getInputStream

 -->
<form action="/file_upload/RegistServlet" method="post" enctype="multipart/form-data">
    使用者:<input name="username" type="text"><br>
    註冊:
<input name="password" type="password"><br> 照片:<input name="pic" type="file" ><br> <input type="submit" value="提交"> </form>
        //獲得複雜型別表單的輸入流
        InputStream in = request.getInputStream();
        //獲得輸入流的內容
        String result = IOUtils.toString(in);

fileUpload的簡單應用

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //建立接受檔案的工廠類
        DiskFileItemFactory factory = new DiskFileItemFactory();
        //建立檔案解析物件
        ServletFileUpload sfu = new ServletFileUpload(factory);
        
        
try { //解析request,獲得表單中的每一檔案(包含普通文字域)項 List<FileItem> list = sfu.parseRequest(request); //遍歷每一個文字項 for(FileItem fi : list){ //獲得原始檔名 String origFileName = fi.getName(); //獲得文字域項的內容 String content = fi.getString(); //獲得文字域的名字 String fieldName = fi.getFieldName(); //文字域的內容的型別 String ContentType = fi.getContentType(); //獲得檔案的大小(以位元組為單位) long size = fi.getSize(); //是否是普通文字(普通文字就是非長傳檔案形式的文字)true代表普通欄位,false是檔案欄位 boolean isFieldForm = fi.isFormField(); System.out.println("原始檔名:"+origFileName); System.out.println("文字項的內容:"+content); System.out.println("文字域的名字:"+fieldName); System.out.println("文字域的內容型別:"+ContentType); System.out.println("檔案大小:"+size); System.out.println("是否是普通欄位:"+isFieldForm); System.out.println("-----------------------------------"); } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } }