1.文件上传的条件
1)表单的提交方式必须是POST方式。(才有content-type属性)
2)有文件上传表单,表单中有<input type="file"/>的选择文件的标签
3)把表单设置为enctype="multipart/form-data",提交的数据不再是key-value对,而是字节数据
# jsp中的代码
<form action="${pageContext.request.contextPath }/UploadDemo1" method="post" enctype="multipart/form-data">
请选择文件: <input type="file" name="img"/><br/>
<input type="submit" value="上传" />
</form>
2.自动书写文件上传的代码
/**
* 手动处理上传文件的逻辑
* @author APPle
*
*/
public class UploadDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//得到实体内容数据
InputStream in = request.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//读取文件的开始符
String startTag = br.readLine();
//读取文件名: Content-Disposition: form-data; name="img"; filename="news.txt"
String line = br.readLine();
String fileName = line.substring(line.lastIndexOf("filename=\"")+10, line.lastIndexOf("\"") );
System.out.println("文件名:"+fileName);
//跳过2行
br.readLine();
br.readLine();
//读取文件的实际内容
String str = null;
BufferedWriter bw = new BufferedWriter(new FileWriter("E:/files/"+fileName));
while((str=br.readLine())!=null){
//读到文件结束符时退出循环
if((startTag+"--").equals(str)){
break;
}
//把内容写出文件中
bw.write(str);
bw.newLine();
bw.flush();
}
//关闭
bw.close();
br.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}