表單提交文件上傳

前言

表單上傳文件是最基本的上傳文件方式,雖然現在有很多優秀的上傳插件,如:webuploader、uploadify等,但我們還是說一下表單上傳。

具體內容

1.jsp頁面form表單

<form name="myform" action="<%=path%>/upload" method="post" enctype="multipart/form-data">
    <input type="text" name="userName" value="" />
    <input type="text" name="age" value="" />
    <input type="file" name="userFile" />
    <input type="submit" value="提交" />
</form>
  • action便是要提交到java的路徑,利用submit提交即可,當然也可以這麼寫,首先給form起名name="myform",然後利用button按鈕點擊事件onClick="doSearch()"方法提交,js代碼如下
function doSearch(){
    document.myform.action=path + "/upload";
    document.myform.target="_self";
    document.myform.submit();
}
  • enctype屬性
    1、application/x-www-form-urlencoded:這是默認編碼方式,它只處理表單域裏的value屬性值,採用這種編碼方式的表單會將表單域的值處理成url編碼方式。
    2、multipart/form-data:這種編碼方式的表單會以二進制流的方式來處理表單數據,這種編碼方式會把文件域指定的文件內容也封裝到請求參數裏。
    3、text/plain:這種方式主要適用於直接通過表單發送郵件的方式。

2.後端java處理上傳文件的架包有3種:

  • commons-fileupload上傳組件
  • COS上傳組件
  • SmartUpload組件

我們只將講commons-fileupload上傳組件,這個組件需要架包commons-fileupload-1.3.3.jar和commons-io-2.5.jar,java代碼如下

 // 判斷enctype屬性是否爲multipart/form-data
boolean isMultipart = ServletFileUpload.isMultipartContent(request);

DiskFileItemFactory factory = new DiskFileItemFactory();

// 當上傳文件太大時,因爲虛擬機能使用的內存是有限的,所以此時要通過臨時文件來實現上傳文件的保存
// 此方法是設置是否使用臨時文件的臨界值(單位:字節)
factory.setSizeThreshold(1024*1024);//1M

// 與上一個結合使用,設置臨時文件的路徑(絕對路徑)
factory.setRepository(new File(request.getSession().getServletContext().getRealPath("")));

Map<String,Object> map =new HashMap<String,Object>();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(1024*1024);// 設置上傳內容的大小限制(單位:字節)
List<?> items = upload.parseRequest(request);
Iterator<?> iter = items.iterator();
while (iter.hasNext()) {
    FileItem item = (FileItem) iter.next();
    if (item.isFormField()) {//如果是普通表單字段
        String name = item.getFieldName();
        String value = item.getString();
        map.put(name, value);
    } else { //如果是文件字段
        String fieldName = item.getFieldName();
        String fileName = item.getName();
        String contentType = item.getContentType();
        boolean isInMemory = item.isInMemory();
        long sizeInBytes = item.getSize();//可以用來判斷文件大小

        if (fileName!=null) {
            File fullFile=new File(item.getName());
            File savedFile=new File(request.getSession().getServletContext().getRealPath(""),fullFile.getName());
            item.write(savedFile);
        } else {
            InputStream uploadedStream = item.getInputStream();
            uploadedStream.close();
        }
    }
}

從代碼中可以看出代碼循環了表單元素,利用item.isFormField()判斷是否是普通字段,普通字段放到了Map裏,文件利用架包上傳,上傳地址爲
request.getSession().getServletContext().getRealPath("")
這個是獲取項目絕對路徑,這個路徑不是新建項目時workspace裏項目路徑,而是項目編譯後的路徑,可以打印看一下。

結語

如果只是上傳文件而沒有其它元素也可以通過字節流實現文件上傳,如下:

 public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
      java.io.InputStream in= request.getInputStream();  
      java.io.FileOutputStream out= new java.io.FileOutputStream("d:\\out.txt");  

      byte[] buffer = new byte[8192];  
      int count = 0;  
      while((count = in.read(buffer)) >0){  
           out.write(buffer, 0, count);  
      }          
      out.close();  
 }  

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章