`

servlet 实现的上传和下载

阅读更多

IE下上传

前端显示
<form action="UploadServlet" method="post">
		<label for="info">信息:</label>
		<input type="text" name="info"><br>
		<label for="file">文件:</label>
		<input type="file" name="file"><br>
		<input type="submit" value="上传">
	</form>

 

后台处理

@WebServlet("/UploadServlet")
public class UploadServlet extends HttpServlet
{
    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException
    {
        request.setCharacterEncoding("UTF-8");
        String filePath = request.getParameter("file");
        System.out.println("filePath========="+filePath);
        File uploadDirPath = new File(getServletContext().getRealPath("/uploadFile"));
        System.out.println("uploadDirPath====="+uploadDirPath);
        if(!uploadDirPath.exists()){
            uploadDirPath.mkdirs();
        }
        String fileName = null;
        if(filePath.indexOf(File.separator)<0){//firefox浏览器取得上传的文件名
             fileName = filePath;
        }
        else{//IE浏览器取得上传的文件名
            fileName = filePath.substring(filePath.lastIndexOf(File.separator)+1);
        }
        
        p(fileName);
        FileInputStream fio = null;
        FileOutputStream fos = null;
        try
        {
             fio = new FileInputStream(filePath);
             fos = new FileOutputStream(uploadDirPath+File.separator+fileName);
            int c;
            while((c=fio.read())!=-1){
                fos.write((char)c);
            }
        }
        catch (Exception e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            fio.close();
            fos.close();
        }
        
        
    }
    
    
    public static void p(Object o){
        System.out.println(o);
    }
    
}

 

 

 

 

 

二。下载

前台界面
<a href="DownLoadServlet?fileName=东软实训总结.doc">东软实训总结.doc</a><BR>
	<a href="DownLoadServlet?fileName=Android_de.rar">Androd.rar</a>

 

后台处理
@WebServlet("/DownLoadServlet")
public class DownLoadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        
        p(getServletContext().getRealPath(""));
        //request.setCharacterEncoding("UTF-8");
        //要下载的文件名
        String fileName = new String(request.getParameter("fileName").getBytes("ISO-8859-1"),"UTF-8");
      //要下载的文件的扩展名
        String fileNameExt = fileName.substring(fileName.indexOf("."));
        System.out.println(fileName);
        //下载文件所在的服务器端的目录
        String downLoadDir = getServletContext().getRealPath(File.separator+"uploadFile");
      //下载文件所在的服务器端的绝对路径
        String downloadPath = downLoadDir+File.separator+fileName;
        p(downloadPath);
        File files = new File(downLoadDir);
        boolean flag = false;
       /* for(File file:files.listFiles()){//查找资源看是否存在
            if(fileName.equals(file.getName())){
                flag = true;
                break;
            }
        }*/
        
        if(new File(downLoadDir,fileName).exists()){
            flag = true;
        }
        
        if(flag){
            p("资源存在");
          //  response.addHeader("content-type", "application/x-download");
            //response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment;filename="+Calendar.getInstance().getTimeInMillis()+fileNameExt);
            //设置文件的大小
           response.addHeader("Content-length", Long.toString(new File(downloadPath).length()));
            FileInputStream fio = new FileInputStream(new File(downloadPath));
            OutputStream fos = response.getOutputStream();
            byte[] b = new byte[1024];
            int n;
            while((n=fio.read(b))!=-1){
                fos.write(b);
            }
            fos.flush();
            fio.close();
            fos.close();
        }
        else{
            response.getWriter().println("资源不存在");
        }
    }
    
    public static void p(Object o){
        System.out.println(o);
    }
}

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics