文件上传原理


参考 Struts 2.X权威指南(第3版)-李刚   第六章第一节

enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码

application/x-www-form-urlencoded 在发送前编码所有字符(默认)
multipart/form-data

不对字符编码。

在使用包含文件上传控件的表单时,必须使用该值。

text/plain 空格转换为 "+" 加号,但不对特殊字符编码。

<!DOCTYPE html>
<html>
<head>
    <meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" />
    <meta http-equiv="Content-Type" content="text/html; charset=GBK" />
    <title> enctype属性测试 </title>
</head>
<body>
<form id="form1" name="form1" 
    enctype="multipart/form-data"
    method="post" action="upload">
    上传文件:<input type="file" name="file" /><br />  
    请求参数:<input type="text" name="wawa" /><br />
    <input name="dd" type="submit" value="提交" />
</form>
</body>
</html>

uploadpro.jsp文件

<%@ page contentType="text/html;charset=GBK" import="java.io.*"%>
<%
InputStream is = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String buffer = null;
while( (buffer = br.readLine()) != null)
{
    if(buffer.endsWith("--") && buffer.startsWith("-----------------------------"))
    {
        break;
    }
    if(buffer.startsWith("-----------------------------"))
    {
        if (br.readLine().indexOf("filename") > 1)
        {
            br.readLine();
            br.readLine();
            File file = new File(request.getRealPath("/") + System.currentTimeMillis());
            PrintStream ps = new PrintStream(new FileOutputStream(file));
            String content = null;
            while( (content = br.readLine()) != null)
            {
                if(content.startsWith("-----------------------------"))
                {
                    break;
                }
                ps.println(content);
            }
            ps.flush();
            ps.close();
        }
    }
}
br.close();
%>







你可能感兴趣的:(文件上传原理)