Servlet文件上传下载

上传

<%@ page contentType="text/html;charset=UTF-8" language="java" %>



    
    Document


    

文件上传

  • 文件上传的表单method属性值必须为post
  • 文件上传控件使用的是input元素type属性值为file
  • 将文件上传的表单form元素的enctype属性值设置为multipart/form-data


下载照片 下载我的照片 下载PDF文件 下载zip文件

上传控制器

package com.kaishengit.web;


@WebServlet("/upload2")
@MultipartConfig
public class FileUploadServlet2 extends HttpServlet {

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.getRequestDispatcher("/WEB-INF/views/upload2.jsp").forward(req,resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      req.setCharacterEncoding("UTF-8");
      String desc = req.getParameter("desc");

      //根据name属性值获取对应的part对象
      Part part = req.getPart("file");
      System.out.println("getName:" + part.getName()); //name属性值
      System.out.println("getContentType:" + part.getContentType()); //文件的MIME类型
      System.out.println("getSize:" + part.getSize()); //上传文件的体积(字节)
      System.out.println("getSubittedFileName:" + part.getSubmittedFileName()); //获取上传的文件名

      //System.out.println(FileUtils.byteCountToDisplaySize(part.getSize()));
      File saveDir = new File("D:/upload");
      if(!saveDir.exists()) {
          saveDir.mkdir();
      }

      String fileName = part.getSubmittedFileName();
      String newName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));

      InputStream inputStream = part.getInputStream();
      FileOutputStream outputStream = new FileOutputStream(new File(saveDir,newName));

      IOUtils.copy(inputStream,outputStream);

      outputStream.flush();
      outputStream.close();
      inputStream.close();

      System.out.println(fileName + "  -> upload success!");


  }
}

下载

   
    下载照片
    下载我的照片
    下载PDF文件
    下载zip文件

下载控制器

package com.kaishengit.web;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

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 java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

@WebServlet("/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String fileName = req.getParameter("file");
        String name = req.getParameter("name");
        //url中含有中文乱码转换
        //fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");
        //System.out.println("fileName:" + fileName);

        File saveDir = new File("D:/upload");

        File file = new File(saveDir,fileName);
        if(file.exists()) {
            if(StringUtils.isNotEmpty(name)) {

                //设置相应的文件头 MIME Type
                resp.setContentType("application/octet-stream");
                //设置文件的总大小
                resp.setContentLength((int) file.length());
                //resp.setContentLengthLong(file.length());
                name = new String(name.getBytes("UTF-8"), "ISO8859-1"); //将浏览器弹出的对话框文字变成中文
                //设置弹出对话框的文件名称
                resp.addHeader("Content-Disposition", "attachment; filename=\"" + name + "\"");

            }

            //响应输出流
            OutputStream outputStream = resp.getOutputStream();
            //文件输入流
            FileInputStream inputStream = new FileInputStream(file);

            IOUtils.copy(inputStream,outputStream);

            outputStream.flush();
            outputStream.close();
            inputStream.close();



        } else {
            resp.sendError(404,"文件找不到");
        }


    }
}

springMvc 上传下载

添加pom依赖


            commons-fileupload
            commons-fileupload
            1.3.2
        


配置springmvc-servlet.xml

 
    
        
    

form表单


控制器

@RequestMapping("/upload")
public String fileupload(String name,MultipartFile file) {
System.out.println("name:" + name);
System.out.println("OriginalFileName:" + file.getOriginalFilename());
System.out.println("size" + file.getSize());
if(!file.isEmpty()) {
InputStream inputStream = file.getInputStream();
//后面的该会了吧
}
return "";
}

package com.xtuer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.ServletContext;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
@Controller
public class UploadController {
    @Autowired
    private ServletContext servletContext;
    /**
     * 上传单个文件的页面
     * @return 页面的路径
     */
    @RequestMapping(value = "/upload-file", method = RequestMethod.GET)
    public String uploadFilePage() {
        return "upload-file.html";
    }
    /**
     * 上传单个文件
     *
     * @param file 上传文件 MultipartFile 的对象
     * @return 上传的结果
     */
    @RequestMapping(value = "/upload-file", method = RequestMethod.POST)
    @ResponseBody
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        saveFile(file);
        return "Success";
    }
    /**
     * 把 HTTP 请求中的文件流保存到本地
     *
     * @param file MultipartFile 的对象
     */
    private boolean saveFile(MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                // getRealPath() 取得 WEB-INF 所在文件夹路径
                // 如果参数是 "/temp", 当 temp 存在时返回 temp 的本地路径, 不存在时返回 null/temp (无效路径)
                String path = servletContext.getRealPath("") + File.separator + file.getOriginalFilename();
                FileCopyUtils.copy(file.getInputStream(), new FileOutputStream(path));
                return true;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}

使用SpringMVC优雅的下载文件

 @GetMapping("/download")
    @ResponseBody
    public ResponseEntity downLoadFile(Integer id) throws FileNotFoundException {
        InputStream inputStream = diskService.downloadFile(id);
        Disk disk = diskService.findById(id);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachement",disk.getSourceName(), Charset.forName("UTF-8"));

        return new ResponseEntity<>(new InputStreamResource(inputStream),headers, HttpStatus.OK);
    }

  @GetMapping("/download")
    public ResponseEntity downloadFile() throws FileNotFoundException {
        File file = new File("E:/upload/12345.jpg");
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        httpHeaders.setContentLength(file.length());
        httpHeaders.setContentDispositionFormData("attachment", "照片.jpg", Charset.forName("UTF-8"));
        InputStreamResource inputStreamResource = new InputStreamResource(new FileInputStream(file));
        return new ResponseEntity(inputStreamResource, httpHeaders, HttpStatus.OK);
    }

poi详解

数据导出excel


    /**
     * 将数据导出为Excel文件
     */
    @GetMapping("/day/{today}/data.xls")
    public void exportCsvFile(@PathVariable String today, HttpServletResponse response) throws IOException {
        List financeList = financeService.findByCreatDate(today);

        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-Disposition","attachment;filename=\""+today+".xls\"");

        //1.创建工作表
        Workbook workbook = new HSSFWorkbook();

        //2.创建sheet页
        Sheet sheet = workbook.createSheet("2017-02-23财务流水");


        //单元格样式(可选)
        /*CellStyle cellStyle = workbook.createCellStyle();
        cellStyle.*/

        //3.创建行 从0开始
        Row row = sheet.createRow(0);
        Cell c1 = row.createCell(0);
        c1.setCellValue("业务流水号");
        row.createCell(1).setCellValue("创建日期");
        row.createCell(2).setCellValue("类型");
        row.createCell(3).setCellValue("金额");
        row.createCell(4).setCellValue("业务模块");
        row.createCell(5).setCellValue("业务流水号");
        row.createCell(6).setCellValue("状态");
        row.createCell(7).setCellValue("备注");
        row.createCell(8).setCellValue("创建人");
        row.createCell(9).setCellValue("确认人");
        row.createCell(10).setCellValue("确认日期");

        for(int i = 0;i < financeList.size();i++) {
            Finance finance = financeList.get(i);

            Row dataRow = sheet.createRow(i+1);
            dataRow.createCell(0).setCellValue(finance.getSerialNumber());
            dataRow.createCell(1).setCellValue(finance.getCreateDate());
            dataRow.createCell(2).setCellValue(finance.getType());
            dataRow.createCell(3).setCellValue(finance.getMoney());
            dataRow.createCell(4).setCellValue(finance.getModule());
            dataRow.createCell(5).setCellValue(finance.getModuleSerialNumber());
            dataRow.createCell(6).setCellValue(finance.getState());
            dataRow.createCell(7).setCellValue(finance.getMark());
            dataRow.createCell(8).setCellValue(finance.getCreateUser());
            dataRow.createCell(9).setCellValue(finance.getConfirmUser());
            dataRow.createCell(10).setCellValue(finance.getConfirmDate());
        }


        sheet.autoSizeColumn(0);
        sheet.autoSizeColumn(1);
        sheet.autoSizeColumn(5);
        sheet.autoSizeColumn(10);
        OutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();

    }

下载zip

控制器
    /**
     * 合同文件的打包下载
     * @param id
     */
    @GetMapping("/doc/zip")
    public void downloadZipFile(Integer id,HttpServletResponse response) throws IOException {
        DeviceRent rent = deviceService.findDeviceRentById(id);
        if(rent == null) {
            throw new NotFoundException();
        } else {
            //将文件下载标记为二进制
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM.toString());
            //更改文件下载的名称
            String fileName = rent.getCompanyName()+".zip";
            fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
            response.setHeader("Content-Disposition","attachment;filename=\""+fileName+"\"");

            OutputStream outputStream = response.getOutputStream();
            ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
            deviceService.downloadZipFile(rent,zipOutputStream);
        }
    }
service
    @Override
    public void downloadZipFile(DeviceRent rent, ZipOutputStream zipOutputStream) throws IOException {
        //查找合同有多少个合同附件
        List deviceRentDocs = findDeviceRentDocListByRentId(rent.getId());
        for(DeviceRentDoc doc : deviceRentDocs) {
            ZipEntry entry = new ZipEntry(doc.getSourceName());
            zipOutputStream.putNextEntry(entry);

            InputStream inputStream = downloadFile(doc.getId());
            IOUtils.copy(inputStream,zipOutputStream);
            inputStream.close();
        }

        zipOutputStream.closeEntry();
        zipOutputStream.flush();
        zipOutputStream.close();
    }

下载zip工具类

package com.toltech.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
* @author Wgs
* @version 1.0
* @create:2018/05/25
*/
public class ZipUtils {
   private ZipUtils(){
   }

   public static void doCompress(String srcFile, String zipFile) throws Exception {
       doCompress(new File(srcFile), new File(zipFile));
   }

   /**
    * 文件压缩
    * @param srcFile 目录或者单个文件
    * @param zipFile 压缩后的ZIP文件
    */
   public static void doCompress(File srcFile, File zipFile) throws Exception {
       ZipOutputStream out = null;
       try {
           out = new ZipOutputStream(new FileOutputStream(zipFile));
           doCompress(srcFile, out);
       } catch (Exception e) {
           throw e;
       } finally {
           out.close();//记得关闭资源
       }
   }

   public static void doCompress(String filelName, ZipOutputStream out) throws IOException{
       doCompress(new File(filelName), out);
   }

   public static void doCompress(File file, ZipOutputStream out) throws IOException{
       doCompress(file, out, "");
   }

   public static void doCompress(File inFile, ZipOutputStream out, String dir) throws IOException {
       if ( inFile.isDirectory() ) {
           File[] files = inFile.listFiles();
           if (files!=null && files.length>0) {
               for (File file : files) {
                   String name = inFile.getName();
                   if (!"".equals(dir)) {
                       name = dir + "/" + name;
                   }
                   ZipUtils.doCompress(file, out, name);
               }
           }
       } else {
           ZipUtils.doZip(inFile, out, dir);
       }
   }

   public static void doZip(File inFile, ZipOutputStream out, String dir) throws IOException {
       String entryName = null;
       if (!"".equals(dir)) {
           entryName = dir + "/" + inFile.getName();
       } else {
           entryName = inFile.getName();
       }
       ZipEntry entry = new ZipEntry(entryName);
       out.putNextEntry(entry);

       int len = 0 ;
       byte[] buffer = new byte[1024];
       FileInputStream fis = new FileInputStream(inFile);
       while ((len = fis.read(buffer)) > 0) {
           out.write(buffer, 0, len);
           out.flush();
       }
       out.closeEntry();
       fis.close();
   }

   public static void main(String[] args) throws Exception {
       doCompress("E:/upload/", "E:/upload.zip");
   }
}


为了更好的演示,首先创建一个文件实体FileBean,包含了文件路径和文件名称:

package com.javaweb.entity;

import java.io.Serializable;
/**
 * 文件实体类*/
public class FileBean implements Serializable{
    
    private static final long serialVersionUID = -5452801884470115159L;
    
    private Integer fileId;//主键
    
    private String filePath;//文件保存路径
    
    private String fileName;//文件保存名称
    
    public FileBean(){
        
    }
       
    //Setters and Getters ...
}    

接下来,在控制层的方法里(示例为Spring MVC),进行读入多个文件List,压缩成myfile.zip输出到浏览器的客户端:

/**
     * 打包压缩下载文件
     */
    @RequestMapping(value = "/downLoadZipFile")
    public void downLoadZipFile(HttpServletResponse response) throws IOException{
        String zipName = "myfile.zip";
        List fileList = fileService.getFileList();//查询数据库中记录
        response.setContentType("APPLICATION/OCTET-STREAM");  
        response.setHeader("Content-Disposition","attachment; filename="+zipName);
        ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
        try {
            for(Iterator it = fileList.iterator();it.hasNext();){
                FileBean file = it.next();
                ZipUtils.doCompress(file.getFilePath()+file.getFileName(), out);
                response.flushBuffer();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            out.close();
        }
    }

你可能感兴趣的:(Servlet文件上传下载)