首页 > 编程语言 > 详细

Java文件上传下载

时间:2019-05-02 00:55:52      阅读:140      评论:0      收藏:0      [点我收藏+]

Java文件上传下载

/**
 * 上传文件
 */
public String uploadFile() throws IOException, Exception {
    
    if (getRequestContext().haveUploadFile()) {

        String channelId = getRequest().getParameter("channelId");
        JfileItem fileItem = getRequestContext().getUploadFiles().get(0);

        // 文件名
        String fileName = fileItem.getName();
        DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
        String uploadFileName = df.format(new Date()) + fileName;

        // 文件类型
        int n = fileName.lastIndexOf(".");
        String type = fileName.substring(n + 1);

        // 上传路径
        String path = getRequest().getServletContext().getRealPath("") + "\\uploadfiles\\";

        //获取输出流
        OutputStream os = new FileOutputStream(path + uploadFileName);
        
        // 获得输入流
        InputStream is = fileItem.getInputStream();
        
        // 写入
        byte[] buffer = new byte[512];
        int temp;
        while ((temp = is.read(buffer)) != (-1)) {
            os.write(buffer, 0, temp);
        }
        os.flush();
        os.close();
        is.close();

        // 将文件信息写入数据库
        FileUpload fileUpload = new FileUpload();
        fileUpload.setFileName(fileName);
        fileUpload.setFileLocation(uploadFileName);
        fileUpload.setFileChannelId(channelId);
        fileUploadService.save(fileUpload);
    }
    return getOutJson().toString();
}

/**
 * 下载文件
 */
public String downloadFile() throws Exception {

    String id = getRequest().getParameter("id");
    FileUpload fileUpload = fileUploadService.getById(id);

    // 根路径
    String path = getRequest().getServletContext().getRealPath("") + "\\uploadfiles\\";

    // 下载文件的路径
    String filePath = path + fileUpload.getFileLocation();

    // 文件名
    String fileName = fileUpload.getFileName();
    fileName = URLEncoder.encode(fileName, "UTF-8");

    HttpServletResponse response = getResponse();

    // 设置文件ContentType类型,自动判断下载文件类型
    response.setContentType("multipart/form-data");
    // 设置编码
    response.setCharacterEncoding("utf-8");
    // 设置文件头,最后一个参数是设置下载文件名
    response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);

    // 通过文件路径获得File对象
    File file = new File(filePath);

    FileInputStream is = new FileInputStream(file);

    // 通过response获取OutputStream对象
    OutputStream os = response.getOutputStream();

    // 写入
    byte[] buffer = new byte[512];
    int i;
    while ((i = is.read(buffer)) != -1) {
        os.write(buffer, 0, i);
    }
    os.flush();
    os.close();
    is.close();

    return getOutJson().toString();
}

Java文件上传下载

原文:https://www.cnblogs.com/creaky/p/10801289.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!