Java - byte[]流实现上传下载(上传byte[]至关系型数据库,下载byte[]流,返回下载链接)

Java - byte[]流实现上传下载(上传byte[]至关系型数据库,下载byte[]流,返回下载链接(ResponseEntity)对象) 

  • 返回 ResponseEntity 实现下载
public ResponseEntity createReportTwo(
//返回 ResponseEntity
            HttpServletRequest request,
            @ApiParam(required = true, name = "token", value = "token") @RequestParam(name = "token", required = true) String token,
            @ApiParam(required = false, name = "orgId", value = "机构id") @RequestParam(name = "orgId", required = true) String orgId,
            @ApiParam(required = true, name = "startTime", value = "开始时间") @RequestParam(name = "startTime", required = true) String startTime,
            @ApiParam(required = true, name = "endTime", value = "结束时间") @RequestParam(name = "endTime", required = true) String endTime
    ){
       

        try {
            String address = this.resultStatisticalServiceImpl.createReport( token,orgId, startTime, endTime );
            Map fileDetal = this.resultStatisticalServiceImpl.getFileDetal( address );
               //fileDetal.get( "buffer" ) byte[]
               //fileDetal.get( "fileName" ) 文件名
            if (null != fileDetal && fileDetal.containsKey( "buffer" ) && null != fileDetal.get( "buffer" )){
                HttpHeaders headers = new HttpHeaders();
                String fileName = encodeFileName(request, fileDetal.get( "fileName" ).toString());
                //attachment 附件属性
                headers.setContentDispositionFormData("attachment", fileName);
                headers.setContentType( MediaType.APPLICATION_OCTET_STREAM);
                //(byte[]) fileDetal.get( "buffer" ) byte[]流 对接
                //HttpHeaders 对象
                //HttpStatus.OK 状态
                return new ResponseEntity((byte[]) fileDetal.get( "buffer" ), headers, HttpStatus.OK);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

 

  • 实体类  (mysql中的类型 data = > longblob)
package com.file.domain;

import javax.persistence.*;
import java.io.Serializable;


@Entity
@Table(name = "tableName")
public class AttachmentFile implements Serializable {

    /**
     * serialVersionUID
     */
    private static final long serialVersionUID = -7262697489461991370L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Lob
    private byte[] data; //@Lob 注解很重要

    @OneToOne(cascade = { CascadeType.ALL })
    @JoinColumn(name = "task_attachment_id")
    private TaskAttachment attachment;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    /**
     * 获得data
     *
     * @return data data
     */
    public byte[] getData() {
        return data;
    }

    /**
     * 设定data
     *
     * @param data data
     */
    public void setData(byte[] data) {
        this.data = data;
    }

    /**
     * 获得attachment
     *
     * @return attachment attachment
     */
    public TaskAttachment getAttachment() {
        return attachment;
    }

    /**
     * 设定attachment
     *
     * @param attachment attachment
     */
    public void setAttachment(TaskAttachment attachment) {
        this.attachment = attachment;
    }
}
  •  upLoad
@Test
	public void upLoadTests() throws IOException {

		File file = new File("C:\\Users\\Chyb\\Desktop\\data.log");
		MultipartFile multipartFile = null;//传值,可以直接获得 MultipartFile 类型数据
		try {
			FileInputStream input = new FileInputStream(file);
			multipartFile = new MockMultipartFile("file", file.getName(), "log", IOUtils.toByteArray(input));
		}catch (Exception e){
			e.printStackTrace();
		}

		System.out.println(multipartFile.getOriginalFilename());

		TaskAttachmentFile taf = new TaskAttachmentFile();
		taf.setData(multipartFile.getBytes());
		TaskAttachmentFile save = this.taskAttachmentFileDao.save( taf );
		System.out.println(save.getId());
	}
  • 上传完成 (data` longblob)
  • Java - byte[]流实现上传下载(上传byte[]至关系型数据库,下载byte[]流,返回下载链接)_第1张图片

 

  • 下载 
@Test
	public void downLoadTests() throws IOException {
		Optional byId = this.taskAttachmentFileDao.findById( 2825L );
		TaskAttachmentFile attachmentFile = byId.get();
		DownloadVo vo = new DownloadVo();
		vo.setData( attachmentFile.getData() );
		HttpHeaders headers = new HttpHeaders();
		String fileName = "newData.log";
		headers.setContentDispositionFormData("attachment", fileName);
		headers.setContentType( MediaType.APPLICATION_OCTET_STREAM);
		// 返回下载文件 , 返回类型 Object
		//@GetMapping(value = "/", produces = MediaType.TEXT_HTML_VALUE) 
		//return ResponseEntity(vo.getData(), headers, HttpStatus.OK);//在Controller 这样返回,类型 Objcet
		System.out.println("DATA : "+vo.getData() + ">" + headers  +">"+ HttpStatus.OK);//这里是测试类, 只做输出流打印
	}
  •  下载实现 (swagger-ui 测试效果)

Java - byte[]流实现上传下载(上传byte[]至关系型数据库,下载byte[]流,返回下载链接)_第2张图片

 

​​​​​​​

随笔记录,方便自己学习

2019-06-19 

 

你可能感兴趣的:(DBA,Java技术)