8

I am new in spring boot.I wanna upload a small file use spring boot and save it in db use jpa. But I don't have good resolution. My program like these:
database table:

CREATE TABLE `report` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) NOT NULL,
  `logo` BLOB NOT NULL,
  `created_time` int(10) NOT NULL,
  `updated_time` int(10) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=13 DEFAULT CHARSET=utf8

jpa bean:
Report.java

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.Table;
import java.io.Serializable;

@Entity
@Table(name="mf_report")
public class Report implements Serializable{
    @Column(name="id")
    private int id;

    @Column(name="name")
    private String name;

    @Lob
    @Column(name="logo", length=100000)
    private byte[] logo;

    public int getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getLogo() {
        return logo;
    }

    public void setLogo(byte[] logo) {
        this.logo = logo;
    }
}

ReportReposity.java:

@Repository
public interface ReportRepository extends CrudRepository<Report,Long>{
}

ReportService.java:

@Service
public class ReportService extends CrudService<Report, ReportRepository> {

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

    @Override
    @Autowired
    public void setRepo(ReportRepository repo) {
        this.repo = repo;
    }

    @Override
    public Report copy(Report from, Report to) {
        to = from;
        return to;
    }

    @Autowired
    private ReportRepository reportRepository;

    public boolean saveReportByRequestBean(ReportAddQueryRequest reportBeanQueryRequest){
    try {
        Report report = new Report();
        report.setName(reportBeanQueryRequest.getName());
        report.setLogo(reportBeanQueryRequest.getLogo());
        long now = System.currentTimeMillis()/1000;
        report.setCreateTime(now);
        report.setUpdateTime(now);
        this.save(report);
    }catch (Exception e){
        logger.error("save report error:", e);
        return false;
    }
    return true;
}
}

ReportParamBean.java:

import org.hibernate.validator.constraints.NotEmpty;
import java.io.Serializable;

public class ReportParamBean extends AbsRequest implements Serializable {
    private long reportId;
    @NotEmpty(message = "Param 'name' can't be NULL")
    private String name;
    private String logo;// In fact, I don't know what type should logo be, File or ?
}

AbsRequest.java:

public class AbsRequest implements Serializable {
    private static final long serialVersionUID = -8928786145900600868L;
    @NotEmpty(message = "Param 'token' can't be NULL")
    @NotNull
    private String token;
    @NotEmpty(message = "Param 'sign' can't be NULL")
    private String sign;
    @Min(value = 1, message = "Param 'time' is invalid")
    private Long time;
    @Min(value = -1, message = "Param 'nodeId' is invalid")
    @NotNull(message = "Param 'nodeId' can't be NULL")
    private Long nodeId;
    private String nodeName;
    @Override
    public String toString() {
        return new ToStringBuilder(this)
                .append("token", token)
                .append("sign", sign)
                .append("time", time)
                .append("nodeId", nodeId)
                .append("nodeName", nodeName)
                .toString();
    }

    public String getToken() {
        return token;
    }

    public void setToken(String token) {
        this.token = token;
    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public Long getTime() {
        return time;
    }

    public void setTime(Long time) {
        this.time = time;
    }

    public Long getNodeId() {
        return nodeId;
    }

    public void setNodeId(Long nodeId) {
        this.nodeId = nodeId;
    }

    public String getNodeName() {
        return nodeName;
    }

    public void setNodeName(String nodeName) {
        this.nodeName = nodeName;
    }
}

ReportController.java:

@RestController
@RequestMapping("/api")
public class ReportController {

    @Autowired
    private ReportService reportService;

    @RequestMapping(value = "/report", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public JSONObject createReport(@RequestBody ReportAddQueryRequest reportBeanQueryRequest){
        boolean result = reportService.saveReportByRequestBean(reportBeanQueryRequest);
        if (!result){
            return ResponseWrapper.buildResponse(RTCodeEnum.C_SERVICE_NOT_AVAILABLE, "add report failed");
        }
        return ResponseWrapper.buildResponse(RTCodeEnum.C_OK, "add report success");
    }
}

I don't know whether I can post a file and other params to server in just one post request,then save the data in db.Could you give me resolution. Special thanks.

Karl Doenitz
  • 2,220
  • 3
  • 20
  • 38

3 Answers3

1

Use Spring's multipart file. In simple implementation you can then get InputStream from it, read the content of the file (being saved on hdd) to a byte array and save it to database.

ps-aux
  • 11,627
  • 25
  • 81
  • 128
0

Consider up voting if this answer help you.

suppose you want to upload a file's data to database then you could do it in two steps:

  1. upload your file as multipart file in your controller class.

    @PostMapping("/uploadYourFile")
    
    public String uploadFile( MultipartFile file) throws IOException {
        FileInputStream inputStream = (FileInputStream) file.getInputStream();
    
        //you can use inputStream object which currently has your "file" data
        // you can process this to fetch your data.
        return  "file uploaded successfully ";
    }
    
  2. Read your uploaded file"inputStream" fetch the data and insert it into your DB through your db query

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Vikash Kumar
  • 1,096
  • 11
  • 10
  • 1
    You might also want to add that the HTML `
    ` tag needs to have a `enctype="multipart/form-data"` Attribute
    – Alexander Feb 25 '19 at 09:30
0

I have made an app to upload, download and delete files to/from database using Spring Boot Rest APIs. I also used Spring Web MultipartFile interface to handle HTTP multi-part requests.

Source code: https://github.com/OusamaELIDRISSI/upload-files-database

Happy coding

Ousama
  • 2,176
  • 3
  • 21
  • 26