Erlo

Java 文件上传下载

2019-02-19 18:01:38 发布   73 浏览  
页面报错/反馈
收藏 点赞

文件实体类

/**
 * 文件实体
 * @author luochen
 */
@Entity
@Table(name = "awards_attachment")
public class AwardsAttachment {
    @Id
    @GeneratedValue
    private Long attachmentId;
    /**
     * 文件类型
     */
    private String attachmentType;
    /**
     * 文件名称
     */
    private String fileName;
    /**
     * 文件路径
     */
    private String filePath;
    /**
     * 创建时间
     */
    private Date createTime;
    /**
     * 修改时间
     */
    private Date updateTime;
    /**
     * 删除标识[1:删除,0正常]
     */
    private String delflag;

    public String getDelflag() {
        return delflag;
    }

    public void setDelflag(String delflag) {
        this.delflag = delflag;
    }

    public Long getAttachmentId() {
        return attachmentId;
    }

    public void setAttachmentId(Long attachmentId) {
        this.attachmentId = attachmentId;
    }

    public String getAttachmentType() {
        return attachmentType;
    }

    public void setAttachmentType(String attachmentType) {
        this.attachmentType = attachmentType;
    }

    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 Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }
}
View Code

 

文件的服务类和实现类就不写了,就是一些增删改查的方法。

 

文件上传控制类

/**
 * 资源下载
 */
@RestController
@RequestMapping("data")
public class DataDownloadController {


    @Autowired
    private AwardsAttachmentService awardsAttachmentService;



    private static final Logger logger = LoggerFactory.getLogger(DataDownloadController.class);

    /**
     * 上传文件
     *
     * @param upfile
     * @param type    文件类型
     * @param request
     */

    @PostMapping("/upload")
    @ApiOperation(value = "上传文件", notes = "上传文件", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ApiImplicitParam(name = "upfile", value = "文件", required = true, dataType = "MultipartFile", paramType = "upfile")
    public JsonResponseExt uploadFile(@RequestParam(value = "file" ) MultipartFile upfile, @RequestParam(value = "type", required = false) String type, HttpServletRequest request) {


        //日期路径
        String baseUrl = new SimpleDateFormat("yyyy/MM/dd").format(new Date()) + "/";

        //String host = request.getHeader("Origin").substring(0, request.getHeader("Origin").lastIndexOf(":")) + ":" + request.getLocalPort();
        String host = request.getScheme()+"://"+request.getServerName() +":"+request.getLocalPort();
        String prePath = "";
        //返回结果集合
        Map map = new HashMap();

        //路径前缀
        prePath = PropertyDbUtil.getPropertiesKey("DataDownload");
        //文件名称
        String fileName = upfile.getOriginalFilename();

        //文件路径
        String path = prePath + baseUrl;

        //存入虚拟目录后的文件名
        //存入虚拟目录后的文件
        File uploadedFile = new File(path, fileName);
        
        File dest = uploadedFile.getParentFile();
        //如果不存在目录就创建
        if (!dest.exists()) {
            dest.mkdirs();
        }
        
        //文件大小限制
        long size = uploadedFile.length() / 1024 / 1024;
        if (size >= 10) {
            return JsonResponseExt.customFail("0032","上传文件的大小不能大于10Mb");
        }
        try {
            //上传
            upfile.transferTo(uploadedFile);
            
            //保存附件
            AwardsAttachment attachment = new AwardsAttachment();
            attachment.setFilePath(uploadedFile.getPath());
            if (!"".equals(type)) {
                attachment.setAttachmentType(type);
            }
            attachment.setFileName(fileName);
            attachment.setCreateTime(new Date());
            attachment.setDelflag("0");
            Long id = awardsAttachmentService.addAttachment(attachment).getAttachmentId();
            //定义返回信息
            String origin = host + "/data/down/" + id;
            map.put("id", id + "");
            map.put("name", fileName);
            map.put("filePath", uploadedFile.getPath());
            map.put("url", origin);

            return JsonResponseExt.success(map);

        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return JsonResponseExt.customFail("0909","上传失败!");
    }




    @GetMapping(value = "/down/{id}")
    public Object demo(@PathVariable("id") String id, String path, HttpServletRequest request, HttpServletResponse response) {

        if (!"".equals(id)) {
            AwardsAttachment tbAttachment = new AwardsAttachment();
            tbAttachment.setAttachmentId(Long.parseLong(id));
            AwardsAttachment awardsAttachment = awardsAttachmentService.findByAttachment(tbAttachment);

            try {
                // 下载本地文件
                String fileName = awardsAttachment.getFileName();
                // 读到流中
                InputStream inStream = new FileInputStream(awardsAttachment.getFilePath());
                // 设置输出的格式
                response.reset();
                //第一步:设置响应类型
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment; filename="" + fileName + """);
                // 循环取出流中的数据
                byte[] b = new byte[100];
                int len;

                while ((len = inStream.read(b)) > 0) {
                    response.getOutputStream().write(b, 0, len);
                }
                inStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return JsonResponseExt.customFail("0033","error");
    }

 

    /**
     * 文件信息
     * @param attachmentInfo
     * @param response
     * @return
     */
    @GetMapping(value = "/downFile")
    public JsonResponseExt fileDownload(AwardsAttachment attachmentInfo, HttpServletResponse response,HttpServletRequest request) {
        Map map = new HashMap();
        String host = request.getScheme()+"://"+request.getServerName() +":"+request.getLocalPort();
        AwardsAttachment info = awardsAttachmentService.findByAttachment(attachmentInfo);
        String origin =host+"/data/down/" + info.getAttachmentId();
        String fileName = info.getFileName();

        map.put("url",origin);
        map.put("name",fileName);
        map.put("path",info.getFilePath());
        return JsonResponseExt.success(map);
    }








}
View Code

 

 

 

页面

class="info-item-status approval" @click="downFile(associatedMsg.creditCodeSample)">class="el-icon-tickets">

//文件下载
    downFile(url){

      var elemIF = document.createElement("iframe");
      elemIF.src = url;
      elemIF.style.display = "none";
      document.body.appendChild(elemIF);

    },
associatedMsg.creditCodeSample为文件路径,类似下面那种路径(路径加上文件id)。为什么用这种路径呢?其实是我的项目是前端和后端是分离的,所以前端的端口和后端的端口号是不一致的,同时如果是
直接根据文件id去访问那个下载接口,我发现是返回的是文件流,并不会自动弹出下载框进行下载。如果是文件流的形式还要弄成Blob类型,而且文件名无法确定,如果要有文件的名称的话
好像还要发一个请求去获取文件的信息。如果存的是下面的链接地址形式,直接点击就会请求这个接口进行下载了。

文件流形式

let url = window.URL.createObjectURL(new Blob([文件流]))
let a= document.createElement('a');
a.style.display = 'none';
a.href = url;
a.setAttribute('download', 文件名称及后缀);
document.body.appendChild(a)
a.click();


 如果你其他的实体类存的是文件的id,可以根据文件id 获取文件信息再下载。[

this.$sysApi.fileMsg() ,这个其实就是一个get方法

]

download(row) {
        this.$sysApi.fileMsg({"attachmentId":row.fileId}).then(res =>{
          console.log(res,"文件");
          var elemIF = document.createElement("iframe");
          elemIF.src = res.data.url;
          elemIF.style.display = "none";
          document.body.appendChild(elemIF);
        });
}

 

登录查看全部

参与评论

评论留言

还没有评论留言,赶紧来抢楼吧~~

手机查看

返回顶部

给这篇文章打个标签吧~

棒极了 糟糕透顶 好文章 PHP JAVA JS 小程序 Python SEO MySql 确认