文件的上传与下载

记录一下文件的上传与下载功能,总是忘记怎么写。。。

  上传:

 //允许上传的后缀名
    public static String[] ALLOWEXTS = new String[]{"jpg","jpeg","gif","png","bmp","pdf","docx","pptx","xlsx","doc","mp3","mp4"};
    /**
     *返回值:String 图片名称
     *作     用:图片上传并返回上传后存储路径
     *参     数:@param file 文件
     *参     数:@param path 上传到路径
     *参     数:@param fileName 外部传递组装文件名称
     * @throws SystemException 
     */
    public static String flieUpload(MultipartFile file, String path, String fileName, HttpServletRequest request) throws SystemException {
        String newName = null;
        if(!file.isEmpty()){
            //文件全名
            String fullName = file.getOriginalFilename();
            //文件后缀名
            String extStr = FileUtil.getExt(fullName);
            //判断是否该类型的文件允许上传
            if(!ArrayUtils.contains(ALLOWEXTS, extStr)){
                logger.error(fullName + "上传文件的类型不匹配!");
                throw new SystemException("上传文件的类型不匹配");
            }else{
                //生成文件名
                newName = fileName + "." + extStr;
                // 获取目标服务器真实路径
                String target = request.getSession().getServletContext().getRealPath("/upload/"+path) + "/" + newName; 
                try {
                    FileUtils.copyInputStreamToFile(file.getInputStream(), new File(target));
                } catch (IOException e) {
                    newName = null;
                    logger.error("上传图片出现错误");
                    e.printStackTrace();
                    throw new SystemException("上传图片出现错误");
                }
            }
        }
         return newName;
    }


下载:

    /**
     * 描述: 下载
     * 参数: @param request
     * 参数: @param response     
     */
    @RequestMapping("/downloadFile")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取要下载的文件名称
        String fileId = request.getParameter("fileId");
        // 根据ID查询到具体内容
        UploadFileInfo uploadFileInfo = uploadFileInfoService.selectByPrimaryKey(fileId);
        if(uploadFileInfo != null) {
            //设置响应头和客户端保存文件名
            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
       // 红字的位置很重要,如果文件名包含中文,不进行转码会乱码 response.setHeader(
"content-disposition", "attachment;fileName=" + new String(uploadFileInfo.getFileName().getBytes("gb2312"), "ISO8859-1")); try { String filePath = request.getSession().getServletContext().getRealPath("/" + uploadFileInfo.getFilePath()); //打开本地文件流 InputStream inputStream = new FileInputStream(filePath); //激活下载操作 OutputStream os = response.getOutputStream(); //循环写入输出流 byte[] b = new byte[2048]; int length; while ((length = inputStream.read(b)) > 0) { os.write(b, 0, length); } // 关闭流 os.close(); inputStream.close(); } catch (IOException e) { throw e; } } }
原文地址:https://www.cnblogs.com/commissar-Xia/p/7407287.html