servlet 3.0 文件上传下载


1.需求场景

利用servlet3.0 实现文件上传

2.项目环境

servlet  jsp  javabean

3.功能实现

package com.demo.action;

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

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


@WebServlet("/uploadServlet")
@MultipartConfig
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");
		response.setContentType("text/html;charset=UTF-8");
		String status="success";
		String fileName="demo";
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 存储路径
		String savePath = request.getServletContext().getRealPath("uploadfile");
		    // 上传单个文件
			// Servlet3.0将multipart/form-data的POST请求封装成Part,通过Part对上传的文件进行操作。
			Part part = request.getPart("file");// 通过表单file控件(<input type="file" name="file">)的名字直接获取Part对象
			// Servlet3没有提供直接获取文件名的方法,需要从请求头中解析出来
			// 获取请求头,请求头的格式:form-data; name="file"; filename="demo.zip"
			String header = part.getHeader("content-disposition");
			// 获取文件名
			String fileName = getFileName(header);
			String filePath = savePath + File.separator + fileName;
			String newFileName = File.separator+System.currentTimeMillis()+".zip";//写成zip后缀,能够在window环境,浏览器下直接下载
			String resultFielPath=savePath+newFileName;
			String downloadpath="uploadfile"+newFileName;
			// 把文件写到指定路径
			part.write(filePath);
			List<String> strlist = FileUtil.readFile(filePath);
			if(strlist!=null && imeilist.size()>0){
				for (int i = 0; i < strlist.size(); i++) {
				       //文件写入
					FileUtil.writeFile(strlist.get(i)+"\t"+result+"\n", resultFielPath);
				}
			}
			request.setAttribute("downloadpath",downloadpath); //文件下载路径
			request.setAttribute("message", "上传解析成功");
			request.setAttribute("status", status);

    	request.getRequestDispatcher("index.jsp").forward(request,response);
	}

	
	/**
	 * 根据请求头解析出文件名
	 * @param header 请求头
	 * @return 文件名
	 */
	public String getFileName(String header) {
		String[] tempArr1 = header.split(";");
		String[] tempArr2 = tempArr1[2].split("=");
		// 获取文件名,兼容各种浏览器
		String fileName = tempArr2[1].substring(tempArr2[1].lastIndexOf("\\") + 1).replaceAll("\"", "");
		return fileName;
	}

}


猜你喜欢

转载自blog.csdn.net/u011625492/article/details/78770297