java web文件读写

好久没写过博客了,最近还是下决心把这个补起来,每隔几天学点技术,通过博客记录下来

文件上传
  1. 前端

这边调用了一个values函数,由于是一个前端展示的是一个list列表,每行的tid都不同,所以传递了一下参数,同时这个button,绑定了一个modal框,modal中设置了上传和下载,主要是下载部分,需要到后端判断文件是否存在,如果存在则下载按钮可以点击,否则不可以点击

<button data-toggle="modal" th:onclick="|javascript:Values(${teacherDoc.tid})|">上传/下载证书文件</button>
function Values(tid) {
$("#keytid").val(tid);//设置到modal中的keytid上面,作为传递依据
    $.ajax({
        url: httptod + "file/existFile",
        type: "post",
        data:{"tid":tid},
        dataType:"json",
        success: function (data) {
            // console.log(data.description);
            if (data.status==0){
                $("#download").attr("disabled",true);
            } else{
                $("#download").attr("disabled",false);
            }
        },
        error: function () {
            console.log("失败");
        }
    })
}

modal部分

<div class="modal fade" id="uploadPdf" tabindex="-1" role="dialog"
     aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"
                        aria-hidden="true">
                    &times;
                </button>
                <h4 class="modal-title" id="myModalLabel">
                    上传文件(PDF格式、大小不超过10M)
                </h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="keytid" value="0"/>
                <input type="file" id="pdffile" class="text-center"
                       name="pdffile"><br>
                <button onclick="uploadpdffile()" type="submit" class="btn btn-primary">提交</button>
                <button id="download" onclick="downpdffile()" type="button" class="btn btn-primary">下载</button>

            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal -->

</div>
上传函数
function uploadpdffile() {
    var tid = $("#keytid").val();
    var formFile = new FormData();
    var file = $("#pdffile")[0].files[0];
    var filetype = getFileType(file.name);
    if (filetype!="pdf" || file.size>=10*1024*1024){
        alert("文件格式错误");  || alert("文件超过10M");
        $("#uploadPdf").modal("hide");
        $("#pdffile").val("");
        return;
    }
    formFile.append("file",file); //加入文件对象
    formFile.append("tid",tid);
    $.ajax({
        url: httptod + "file/upload",
        type: "post",
        data: formFile,
        processData: false,//用于对data参数进行序列化处理 这里必须false
        contentType: false, //必须
        dataType: "json",
        success: function (data) {
            alert(data.description);
            $("#uploadPdf").modal("hide");
            $("#pdffile").val("");
        }
    })
}

//由于文件需要为pdf格式,我在这里没有传递到后台判断,在前台判断了一下文件的后缀名,可能比较简陋
function getFileType(filePath) {
    var startIndex = filePath.lastIndexOf(".");
    if(startIndex != -1)
        return filePath.substring(startIndex + 1, filePath.length).toLowerCase();
    else return "";
}

  1. 后端

//文件上传,这里,我对java在web下的存储位置还是存在问题,所以存储地方都放在了绝对路径上面
每个list中id都只对应一个文件,如果一个人对某个文件反复上传,则会先进行删除原来文件,然后更新数据库存储的文件地址,达到覆盖效果
MultipartFile 这里还是用到MultipartFile ,多文件上传,但是实际只存储了单文件,后面感觉多文件在数据库中的存储方式,还是需要考虑一下,如何存储
这个MultipartFile 的优点是有一个transferTo,设置了文件地址后,直接就能把文件存储好

    String filePath = "C:\\Users\\DELL\\Desktop\\wordtemplate\\";
//    String filePath = "/usr/word/";   linux系统
    @PostMapping("/upload")
    @ResponseBody
    public Result upload(HttpSession session, @RequestParam("file")MultipartFile file, @RequestParam("tid") String tid){
        UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
        //首先  先去查询  查询出来之后 ,删除  然后覆盖
        FileSavePath fileSavePath = new FileSavePath(user.getNumber(),user.getRoletype(),Integer.valueOf(tid));
        FileSavePath fileOld = fileSavePathService.selectFileSavePath(fileSavePath);
        if (fileOld!=null){
            //删除文件
            File OldDelete = new File(filePath+fileOld.getFilename());
            OldDelete.delete();
            fileSavePathService.deleteFileSavePath(fileOld);
        }
        if (file.isEmpty()){
            return new Result(0,"上传失败,请选择文件");
        }
        String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date())
                +file.getOriginalFilename();
        File dest = new File(filePath+fileName);
        try {
            file.transferTo(dest);
            fileSavePath.setFilename(fileName);
            //只存储一下文件名
            fileSavePathService.insertFileSavePath(fileSavePath);  //存储文件路劲
            return new Result(1,"上传成功");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new Result(0,"上传失败");
    }
文件下载
  1. 前端

在modal中,有一个点击框哪里,调用此函数
这里有一段最初考虑思路,最开始其实在modal中没有keyid,也就是没有单独设立id,也没有用一点击调用modal框,就进行判断文件是否存在,然后想到用post方法,传递tid到后台,然后如果可以下载,就下载,不能下载,就不下载
然而,主要问题出现在返回数据上面,不存在返回json数据,存在下载文件为response做出的响应,两者之间存在冲突。找到一个解决思路是:在这段ajax中,先调用一个文件是否存在的函数,然后再调用下载函数,其中,由于用到post方法,所以使用innerhtml方法,添加一个form 表格,设置input id为hidden来获取。
最终,改来改去,成了最初的点击model前,就进行判断文件是否存在,不存在则下载按钮无法点击
参考到的post不推荐做文件下载

//文件下载
function downpdffile() {
    var tid = $("#keytid").val();
    window.location.href = httptod + 'file/download?tid=' + tid;
    $("#uploadPdf").modal("hide");
}
  1. 后端

//文件是否存在函数

@PostMapping("/existFile")
    @ResponseBody
    public Result existFile(HttpSession session,@RequestParam ("tid") String tid){
        UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
        FileSavePath fileSavePath = new FileSavePath(user.getNumber(),user.getRoletype(),Integer.valueOf(tid));
        fileSavePath = fileSavePathService.selectFileSavePath(fileSavePath);
        if (fileSavePath==null){
            return new Result(0,"文件不存在");
        }else{
            return new Result(1,"文件存在");

        }
    }

下载核心代码,使用到了response,但是使用到前后端分离后,是否就没有response可用了呢?

    @GetMapping("/download")
    public void download(HttpSession session,HttpServletResponse response,@RequestParam ("tid") Integer tid) throws Exception {
        UserInfo user = (UserInfo) session.getAttribute("USER_SESSION");
        //首先  先去查询  查询出来之后 ,删除  然后覆盖
        FileSavePath fileSavePath = new FileSavePath(user.getNumber(),user.getRoletype(),Integer.valueOf(tid));
        fileSavePath = fileSavePathService.selectFileSavePath(fileSavePath);

        File file = new File(filePath+fileSavePath.getFilename());
        // 穿件输入对象
        FileInputStream fis = new FileInputStream(file);
        // 设置相关格式
        response.setContentType("application/force-download");
        // 设置下载后的文件名以及header
        response.addHeader("Content-disposition", "attachment;fileName=" +new String(fileSavePath.getFilename().getBytes("utf-8"),"ISO8859-1"));
//        fileSavePath.getFilename()
        // 创建输出对象
        OutputStream os = response.getOutputStream();
        // 常规操作
        byte[] buf = new byte[1024];
        int len = 0;
        while((len = fis.read(buf)) != -1) {
            os.write(buf, 0, len);
        }
        fis.close();
    }
其它下载使用过的代码

//导出为excel表格的下载

@GetMapping(value = "/ExcelBrief")
    public void ExcelBrief(HttpSession session,HttpServletResponse response) {
        List<BriefTeacher> briefTeachers = teacherDocService.selectBrief("3");

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
        //导出为excel表格
        String[] title = new String[]{"申请日期", "通过日期"};
        String[][] data = new String[briefTeachers.size()][];
        for (int i = 0; i < briefTeachers.size(); i++) {
            data[i] = new String[8];
            data[i][0] = briefTeachers.get(i).getDepartment();
            data[i][1] = briefTeachers.get(i).getTusername();
            // ~~~
            data[i][6] = sf.format(briefTeachers.get(i).getAdate());
            data[i][7] = sf.format(briefTeachers.get(i).getSuredate());
        }

        //创建文件名
        String fileName = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date())+".xls";
        HSSFWorkbook wb = ExcelUtils.getHSSFWorkbook("汇总表格", title, data, null);
        //响应到客户端
        try {
            this.setResponseHeader(response, fileName);
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 发送响应流方法
     */
    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(), "ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

//导出为doc文件的下载
//调用的转化为doc的代码,能传递回一个file
//这里出现的一个败笔就是,先在文件系统中创建出来了这个word,然后下载后,然后又删除掉,以后考虑是否可以参考导出excel的方式,形成file之后,直接下载,不保存在系统中
参考到的添加链接描述
添加链接描述
添加链接描述

@GetMapping(value = "/translateDoc")
    public void translateDoc(String tid, HttpServletResponse response) throws IOException {
        TeacherDoc teacherDoc = teacherDocService.selectTeacherDocSingle(tid);
        HashMap<String, String> stringStringHashMap = Translate.TeacherToMap(teacherDoc);
        InputStream fin = null;
        ServletOutputStream out = null;
        File file = null;
        try {
            Freemark freemark = new Freemark();
            file = freemark.UseFreemark(stringStringHashMap);
            if (file.isFile()) {
                System.out.println("存在");
            } else {
                System.out.println("不存在");
            }
            // 调用工具类的createDoc方法生成Word文档  
            fin = new FileInputStream(file);
            response.setCharacterEncoding("utf-8");
            response.setContentType("application/msword");
            // 设置浏览器以下载的方式处理该文件名  
//            String fileName = title+ DateUtil.formatDateDetailTime(new Date()) + ".doc";
            String fileName = file.getName();
            response.setHeader("Content-Disposition", "attachment;filename="
                    .concat(String.valueOf(URLEncoder.encode(fileName, "UTF-8"))));
            out = response.getOutputStream();
            byte[] buffer = new byte[512]; // 缓冲区  
            int bytesToRead = -1;
// 通过循环将读入的Word文件的内容输出到浏览器中  
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } finally {
            if (fin != null) fin.close();
            if (out != null) out.close();

            if (file != null) file.delete(); // 删除临时文件  
        }
    }

//freemark 生成word的代码

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 使用freemark生成word
 * @author stormw
 */
public class Freemark {
	
	public  File UseFreemark(HashMap<String,String> stringStringHashMap) throws IOException {

		Freemark freemark = new Freemark();
		freemark.configuration = new Configuration();
		freemark.configuration.setDefaultEncoding("utf-8");
		freemark.configuration.setDirectoryForTemplateLoading(new File("C:\\Users\\DELL\\Desktop"));
//		freemark.configuration.setDirectoryForTemplateLoading(new File("/usr/"));


		freemark.setTemplateName("haode.ftl");
		freemark.setFileName(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").format(new Date())+".doc");
		freemark.setFilePath("C:\\Users\\DELL\\Desktop\\wordtemplate\\");
//		freemark.setFilePath("/usr/word/");
		File file = freemark.createWord(stringStringHashMap);
		
		return file;
	}
	//下载生成的代码
	private File createWord(Map map){
		Template t = null;
		File outFile = new File(filePath+fileName);
		Writer out = null;
		try {
			t = configuration.getTemplate(templateName);
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
			t.process(map, out);
			out.close();
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return outFile;
	}
	

	
	/**
	 * freemark模板配置
	 */
	private Configuration configuration;
	/**
	 * freemark模板的名字
	 */
	private String templateName;
	/**
	 * 生成文件名
	 */
	private String fileName;
	/**
	 * 生成文件路径
	 */
	private String filePath;

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getTemplateName() {
		return templateName;
	}

	public void setTemplateName(String templateName) {
		this.templateName = templateName;
	}
	
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值