欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java Web实用开发技术-文件的上传与下载

程序员文章站 2022-07-12 19:00:38
...

(需要将cos.jar放入lib目录下)
文件上传页面upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="upload" method="post" enctype="multipart/form-data">
	<input type="file" name="file1"><br>
	<input type="submit" value="上传">
</form>
</body>
</html>

执行上传操作的Servlet(地址为upload)

package Servlet;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String saveDirectory="d:\\tools\\upload";//即上传到服务器的D盘目录
		File savedir=new File(saveDirectory);
		if(!savedir.exists()){
			savedir.mkdirs();//若路径不存在,则创建它
		}
		int maxPostSize=5*1024*1024;//上传大小限制:5MB
		//若上传的文件重名,则默认覆盖原先的文件
		MultipartRequest multi;
		multi=new MultipartRequest(request,saveDirectory,maxPostSize,"utf-8");
		/*
		 * 下述代码若上传的文件重名,会自动为新文件重新命名(文件名后加序号01,02...)
		 * FileRenamePolicy policy=(FileRenamePolicy)new DefaultFileRenamePolicy();
		 * MultipartRequest multi;
		 * multi=new MultipartRequest(request,saveDirectory,maxPostSize,"utf-8");
		 */
		//若想获得上传的文件和表单的其他元素的信息,可借助于MultipartRequest类型的对象multi
		//在控制台上显示文件信息
		Enumeration<String> files=multi.getFileNames();
		while(files.hasMoreElements()){
			String name=files.nextElement();
			File f=multi.getFile(name);
			if(f!=null){
				String fileName=multi.getFilesystemName(name);
				String lastFileName=saveDirectory+"\\"+fileName;
				System.out.println("上传的文件:"+lastFileName);
			}
		}
	}

}

执行下载操作的Servlet(地址为download)

package Servlet;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.ServletUtils;

/**
 * Servlet implementation class DownloadServlet
 */
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DownloadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String filepath="d:/";//下载路径
		String filename="1.jpg";//下载的文件名
		String guessCharset="UTF-8";
		try{//使用iso-8859-1编码方式
			String isofilename=new String(filename.getBytes(guessCharset),"iso-8859-1");
			response.setContentType("application/octet-stream");
			response.setHeader("Content-Disposition", "attachment;filename"+isofilename);
			ServletOutputStream out=null;
			out=response.getOutputStream();
			ServletUtils.returnFile(filepath+filename,out);//下载文件
		}catch(UnsupportedEncodingException ex){//iso8859_1编码异常
			ex.printStackTrace();
		}catch(IOException e){//getOutputStream()异常
			e.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}

【实例】上传作业,上传的作业命名格式为“学号-题号”,要求上传到服务器后将文件重命名为“客户端IP地址-学号-题号”形式,可上传多次,后上传的文件将覆盖先前上传的文件。

上传页面upload.jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="Upload" method="post" enctype="multipart/form-data">
	<input type="file" name="file1" contenteditable="false"
	onclick="info.innerHTML=''"><br>
	<input type="submit" value="上传">
</form>
<div id="info">${message }</div>
</body>
</html>

处理上传的Servlet(地址为Upload)

package Servlet;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oreilly.servlet.MultipartRequest;

/**
 * Servlet implementation class Upload
 */
@WebServlet("/Upload")
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Upload() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String requestip=request.getRemoteAddr();
		String saveDirectory=this.getServletContext().getRealPath("")+"\\Upload";
		File savedir=new File(saveDirectory);
		if(!savedir.exists()){
			savedir.mkdirs();//若路径不存在,则创建它
		}
		int maxPostSize=5*1024*1024;//上传大小限制:5MB
		//若上传的文件重名,则默认覆盖原先的文件
		MultipartRequest multi;
		multi=new MultipartRequest(request,saveDirectory,maxPostSize,"utf-8");
		Enumeration<String> files=multi.getFileNames();
		String name=files.nextElement();
		File f=multi.getFile(name);
		if(f!=null){
			String fileName=f.getName();
			File sServerFile=new File(saveDirectory+"\\"+requestip+"-"+fileName);
			if(sServerFile.exists()){
				sServerFile.delete();
			}
			f.renameTo(sServerFile);
			String message="文件上传成功!文件名为:"+requestip+"-"+fileName;
			request.setAttribute("message", message);
		}
		request.getRequestDispatcher("/upload.jsp").forward(request, response);
	}

}

相关标签: Java Web