现在的位置: 首页 > 综合 > 正文

Servlet 上传与下载

2017年12月26日 ⁄ 综合 ⁄ 共 5089字 ⁄ 字号 评论关闭

Servlet两种上传方法:

/**
 * @Version: 1
 * @JDK: jdk 1.7
 * @Module: fileupload

 * 2012-6-8 - 下午8:48:35 Created by Sharp
 */ 

 /*- 				History
 **********************************************
 *  ID      DATE           PERSON       REASON
 *  1     2012-6-8         Sharp        Created
 **********************************************
 */

package com.sharp.servlet;

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;

import org.apache.catalina.core.ApplicationPart;
import org.apache.commons.io.FileUtils;

import com.jspsmart.upload.SmartUpload;
import com.sharp.pojo.Book;
//必需的annotation,要不然上传不了
@MultipartConfig(maxFileSize=10240000)//必需的annotation
@WebServlet(urlPatterns="/upload.action")
public class FileUploadServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		/**
		 * 
		 * servlet 3.0 上传
		 * 
		 * */
//		ApplicationPart part = (ApplicationPart)req.getPart("filename");//单文件上传
		List<Part> parts = (List<Part>)req.getParts();
		for(Part part : parts){
			System.out.println("content-type--->" + part.getContentType());
			if(part.getContentType() == null){
				System.out.println(part.getName());
				System.out.println(req.getParameter(part.getName()));
			}else{
				ApplicationPart p = (ApplicationPart)part;
				if(p.getSize()>0){
					System.out.println(p.getContentType());
					String fileName = p.getFilename();
					p.getHeader("content-disposition");
					System.out.println("fileName-------->" + fileName);
					System.out.println(p.getSize());
					String name = req.getParameter("username");
					System.out.println("name----->" + name);
					FileUtils.copyInputStreamToFile(p.getInputStream(),new File(this.getClass().getResource("/").getPath(), fileName));
				}
				continue;
			}
		}
		
		
		/**
		 * 
		 * fileupload组件上传
		 * 
		 **/
		
		/*DiskFileItemFactory factory = new DiskFileItemFactory();
		File temp_dir = new File(this.getClass().getResource("/").getPath() + "temp" + File.separator);
		autoMkdirs(temp_dir.getPath());
		String save_dir = this.getClass().getResource("/").getPath() + "images";
		autoMkdirs(save_dir);
		factory.setRepository(temp_dir);
		factory.setSizeThreshold(1024*1024);
		ServletFileUpload upload = new ServletFileUpload(factory);
		try {
			List<FileItem> fileItems = upload.parseRequest(req);
			for(FileItem fileItem : fileItems){
				if(fileItem.isFormField()){
					String fileName = fileItem.getFieldName();
					String fileValue = fileItem.getString();
					System.out.println("fileName------------>" + fileName);
					System.out.println("fileValue------------>" + fileValue);
					
				}else{
					String fileName = fileItem.getName();
					fileItem.write(new File(save_dir, fileName));
				}
			}
			req.getRequestDispatcher("listfiles.action").forward(req, resp);
		} catch (Exception e) {
			e.printStackTrace();
		}*/
		
		/**
		 * smartUpload组件上传
		 * */
/*		Book book = new Book();
		//创建SmartUpload对象
		SmartUpload mySmartUpload = new SmartUpload();
		//SmartUpload的初始化,使用这个jspsmart一定要在一开始就这样声明
		mySmartUpload.initialize(getServletConfig(),req,resp);
		//上传所有内容
		mySmartUpload.upload();
		//SmartUpload对象将上传的文件封装到File里面
		com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
		if (!myFile.isMissing()) { //如果有文件就保存
			//将文件存放于绝对路径的位置+文件名,SAVE_VIRTUAL指示组件将文件保存到以Web应用程序根目录为文件根目录的目录下
			myFile.saveAs("/images/book/" + myFile.getFileName(),SmartUpload.SAVE_VIRTUAL);
			//将封面名称保存到数据库
			System.out.println("file name------------>" + myFile.getFileName());
			
			book.setImage( myFile.getFileName());
		}
		*//**%%%%%%%%%%%%%%%%%%%封面图片上传结束%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*//*
		//用了enctype= "multipart/form-data " 就不能getParmeter了因为 他是一个特殊的标记
		com.jspsmart.upload.Request smartRequest = mySmartUpload.getRequest();
		//添加数据到数据库
		
		String title = smartRequest.getParameter("title");*/
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}
	
	public void autoMkdirs(String dir){
		File file = new File(dir);
		if(!file.exists()){
			file.mkdirs();
		}
	}
}

 

Servlet下载:

 

/**
 * @Version: 1
 * @JDK: jdk 1.7
 * @Module: fileupload

 * 2012-6-8 - 下午9:33:36 Created by Sharp
 */ 

 /*- 				History
 **********************************************
 *  ID      DATE           PERSON       REASON
 *  1     2012-6-8         Sharp        Created
 **********************************************
 */

package com.sharp.servlet;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

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 org.apache.commons.io.FileUtils;
@WebServlet(urlPatterns="/download.action")
public class FileDownload extends HttpServlet{
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		resp.setCharacterEncoding("UTF-8");  
        
        String filename=req.getParameter("fileName");  
        filename = new String(filename.getBytes("iso-8859-1"),"utf-8");
        File destFile = new File(this.getClass().getResource("/").getPath()+ "images/" + filename);
        // 设置内容格式  
//        resp.setContentType("text/x-msdownload");  
          
        resp.setCharacterEncoding("UTF-8"); 
          
        // 设置文件头信息  
        resp.setHeader("Content-disposition","attachment; filename="+new String(filename.getBytes("utf-8"),"iso8859-1"));  
           
        OutputStream os = resp.getOutputStream();  
        FileUtils.copyFile(destFile, os);
        os.close();
	}
}

 

抱歉!评论已关闭.