在 Servlet 3.0 中處理 multipart/form-data 請(qǐng)求的兩個(gè)輔助方法 |
Two Assistant Methods for Dealing with multipart/form-data Request in Servlet 3.0 |
Servlet 3.0 引入了 javax.servlet.http.Part 接口,從而提供了對(duì) multipart/form-data 類型的 HTTP 請(qǐng)求的直接支持,我們從此就可以擺脫諸如 Apache Commons FileUpload 之類的第三方依賴。然而,該支持太過單純,所以還要多做點(diǎn)事情,以便能更有效地進(jìn)行工作。我將在本文中介紹兩個(gè)輔助方法。 |
Servlet 3.0 comes with out-of-the-box support for handling HTTP request of type multipart/form-data by introducing of javax.servlet.http .Part interface, freeing us from 3rd party dependencies such as Apache Commons FileUpload. However, the support so pure that we still need to do a little more work to get us work more effective. I'll demostrate two assistant methods in this article. |
首先,Servlet 3.0 沒有提供方法將 Part 對(duì)象專為字符串。multipart/form-data 請(qǐng)求也可能包含字符串參數(shù)。在這種情況下,我們可以寫一個(gè)工具方法來從 Part 對(duì)象讀取字節(jié),然后將其解析為字符串。為了方便,還可以讓這個(gè)方法能處理最常見的 application/x-www-form-urlencoded 請(qǐng)求: |
First, there's no method to translate a Part object to a string value in Servlet 3.0. A multipart/form-data request may also contain string parameters. In this case, we can wrtie a utility method to read bytes from the Part object and parse them to a string value. For convenience we also enable the method to handle the most common application/x-www-form-urlencoded request: |
-
-
-
-
-
-
-
-
-
-
-
- public static String getParameter(HttpServletRequest req, String name,String charse) {
-
- String value = req.getParameter(name);
- if (value != null) {
- return value;
- }
-
- try {
- Reader in = new InputStreamReader(part.getInputStream(), charset);
- StringBuilder sb = new StringBuilder();
- char[] buffer = new char[256];
- int read = 0;
- while ((read = in.read(buffer)) != -1) {
- sb.append(buffer, 0, read);
- }
- in.close();
- return sb.toString();
- } catch (Exception ex) {
- return null;
- }
- }
|
類似地,可以寫一個(gè) getParameterValues 方法去處理名稱相同的多個(gè)參數(shù),所以就不在這里列出代碼了。第二個(gè)輔助方法用于從 Part 對(duì)象獲取文件名。Part 接口并沒有提供這種方法,但我們可以容易地從頭部提取出文件名: |
In the similar manner we can write a getParameterValues method to handle multiple parameter with the same name, so I'm not going to list the code here. The sencond assistant method is for getting the filename from a Part object. The Part interface doesn't provide such a method, but we can easily extract the filename from the header: |
- private static final String FILENAME_KEY = "filename=\"";
-
-
-
-
-
-
-
- public static String getFileNameFromPart(Part part) {
- String cdHeader = part.getHeader("content-disposition");
- if (cdHeader == null) {
- return null;
- }
- for (String s : cdHeader.split("; ")) {
- if (s.startsWith(FILENAME_KEY)) {
-
-
-
- String path = s.substring(FILENAME_KEY.length(),
- s.length() - 1).replaceAll("\\\\", "/");
- return path.substring(path.lastIndexOf("/") + 1);
- }
- }
- return null;
- }
|