实验九文件的上传与下载--web

一、实验目的
理解和巩固课堂上所学的文件上传与下载的开发与使用方法,提高学生对知识的实际运用与软件编程实现能力。
二、实验内容
设计实现一个文件上传程序。具体步骤如下:1. 编写第1个jsp页面index.jsp,其中有一个form,用于选择要上传的文件。2. 编写第2个jsp页面upload.jsp,用于处理文件上传。3. 上传的文件存放在myupload文件夹中。
三、实验要求

  1. 文件名字不要使用中文,文件名字首字母小写。2. 第一个文件命名为为index.jsp。3. 所有文件打成一个文件压缩包提交。压缩包文件命名规则:计181-01-姓名。4. 在程序中的title或者注释等地方加入个人名字信息。5. 提交程序运行成功结果截图,可以截多张图。

//index.jap

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">   
    <title>xxx</title>
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0">    
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css">
 -->
  </head>
  <body>
    <form action="/zuoyes/upload.jsp" enctype="multipart/form-data" method="post">
     <p> <input type="file" name="file"/> <br>
     <p> <input type="submit" name="上传"/>
    </form>
  </body>
</html>

//upload.jsp

<%@ page contentType="text/html; charset=gb2312" language="java"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.util.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="java.io.*"%>
<% 
 ServletFileUpload upload = new ServletFileUpload();  
 FileItemIterator iter = upload.getItemIterator(request);
 while (iter.hasNext()) 
 {
    
    
     FileItemStream item = iter.next();
     String name = item.getFieldName();
     InputStream stream = item.openStream();
     if (item.isFormField()) {
    
    
           out.println(name + "="+ Streams.asString(stream) );    
       } 
     else 
     {
    
    
         out.println(name + "="  + item.getName());
      String filename=new File(item.getName()).getName();
   out.print("File name:"+filename);
   BufferedInputStream bis=new BufferedInputStream(stream);
   String sitePath=application.getRealPath("/myupload");
   File f1=new File(sitePath+"/"+filename);
   FileOutputStream fo=new FileOutputStream(f1);
   BufferedOutputStream bos=new BufferedOutputStream(fo);
   Streams.copy(bis, bos, true);
        }
       out.println("<br>");
 }                
%>

//在WebRoot下建一个包myupload

Guess you like

Origin blog.csdn.net/weixin_45800653/article/details/107956366