jsp中 input type=file 上传附件的实现原理

2025-04-05 03:55:49
推荐回答(1个)
回答1:

当一个form表单 被设置为enctype="MULTIPART/FORM-DATA" method="post" 时,其中的〈input type="file" name="filename" /> 标签如果被用户 选择了文件的话.
浏览器会把 文件内容连同 form的所有字段 格式化后传递到服务器~~
如下
一个测试:

<%@ page contentType="text/html;charset=GB2312"%>


选择要上传的文件:










处理:
[color=green]

<%@ page contentType="text/html;charset=GB2312"%>
<%@ page import="java.io.*"%>


<%try{InputStream in=request.getInputStream();
File f=new File("f:\\qin\\jsp","a.txt");
FileOutputStream o=new FileOutputStream(f);
byte b[]=new byte[1024];
int n;
while((n=in.read(b))!=-1)
{o.write(b,0,n);
}
o.close();
in.close();

}
catch(IOException ee){}
out.print("文件已经上传");
%>