ajaxFileUpload上传、下载

494 阅读1分钟

在web项目中,使用ajaxfileupload插件上传文件时,首先需要引入ajaxfileupload.js

    <input type=”file” class=”upload-btn” id=”czPath” name=”file”>
    function uploadHanlelogFj(handleLogId) {
    var fileEleId = “czPath”; //这里和标签的id对应
    var attrName = “file”; //这里和标签的name对应
    //单个文件的异步上传
    $.ajaxFileUpload({
        type: “POST”,
        url: “eventManager/uploadHandleLogFj”,
        fileElementId: fileEleId,
        dataType: “text”,
        data: {
            attrName: attrName,
            eventHandlogId: handleLogId
            }
        });
    }
    使用字节流上传文件
public class UpAndDownLoadUtil {

/**
 * Ajax上传文件
 * @param request
 * @param attrName 标签的name属性
 */
public static String  ajaxUpload(HttpServletRequest request,String attrName){

    MultipartHttpServletRequest request1=(MultipartHttpServletRequest) request;
    MultipartFile mFile = request1.getFile(attrName);
    //文件上传的位置(在web项目时指的是out文件夹)
    String path = request.getSession().getServletContext().getRealPath("/uploads/");
    //判断该路径是否存在
    File file=new File(path);
    if(!file.exists()){
        // 创建文件夹
        file.mkdirs();
    }
    String outPath=null;
    String fileName = mFile.getOriginalFilename(); //得到的就是上传时文件的原名
    if(StringUtil.isValidStr(fileName)){
        String uuid1 = UUID.randomUUID().toString().replace("-", "");
        fileName=uuid1+"@@@@"+fileName;
        //获取当前系统下的文件分隔符
        String property = System.getProperty("file.separator");
        outPath=path+property+fileName;
        //字节流上传文件
        try(OutputStream outputStream = new FileOutputStream(outPath);
            InputStream inputStream = mFile.getInputStream();){
            byte[] buffer = new byte[4096];
            int length = 0;
            while((length = inputStream.read(buffer)) != -1){
                outputStream.write(buffer, 0, length);
            }

        } catch (IOException ioe){
            ioe.printStackTrace();
            return null;
        }
    }
    return fileName;
}
/**
 * 文件下载(字节流)
 * @param response
 * @param FileName 文件路径
 * @return
 */
public static void downLoad(HttpServletResponse response, HttpServletRequest request,String FileName){
    if(FileName!=null){


        String path = request.getSession().getServletContext().getRealPath("/uploads/");
        //获取当前系统下的文件分隔符
        String property = System.getProperty("file.separator");
        path=path+property+FileName; //得到文件的绝对路径
        //设置文件路径
        File file=new File(path);
        //文件名
        String name =FileName;
        if (FileName.contains("@@@@")){
            name=FileName.substring(FileName.substring(0, FileName.indexOf("@")).length() + 4, FileName.length());
        }
        if(file.exists()){
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;filename="+new String(name.split("@@@@")[0].getBytes("utf-8"),"ISO-8859-1"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try{
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    os.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
}

若在页面上通过发送请求到后端下载文件时,不可以使用ajax,因为ajax请求是字符流,但是读写文件(上传下载文件的本质就是读写文件)是字节流,所以前端通过发送请求下载文件时,选择通过表单方式。这种方式也可以使得浏览器有下载提示。

$('< form method="post" action="/eventManager/test/">').appendTo('body') .submit().remove();