今日学习了文件的简单的上传:
要想实现文件上传,要将<input>标签的type设为“file”,而且form表单的method方法必须为post,
不然只会上传文件的名字,form表单还要设置enctype属性为:multipart/form-data。这是将文件转化为二进制流。
在servlet中使用InputStream接受,inputstream=req.inputStream();之后的操作与java读写文件一样。
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub InputStream inputstream=req.getInputStream(); Reader reader=new InputStreamReader(inputstream); BufferedReader buffreader=new BufferedReader(reader); OutputStream outputstream=new FileOutputStream("F:\\copy.txt"); Writer writer=new OutputStreamWriter(outputstream); BufferedWriter buffwriter=new BufferedWriter(writer); String str=""; while((str=buffreader.readLine())!=null) { System.out.println(str); buffwriter.write(str+"\n\r"); } buffreader.close(); buffwriter.close(); reader.close(); inputstream.close(); outputstream.close(); writer.close(); }