Feezan Khattak
Feezan Khattak

Reputation: 222

Adding Extra Data with File upload using springBoot and ReactJs

Hope you are all fine, I got a serious problem while uploading a file with some extra data in spring boot, here is my upload file java code

// Add new AssignmentList List Record
    @PostMapping("/uploadfile")
    public ResponseEntity<String> uploadData(@RequestParam("document") MultipartFile file) throws Exception {
        try {
            String fileName = StringUtils.cleanPath(file.getOriginalFilename());
            AssignmentList  assignmentList = new AssignmentList();
            assignmentList.setFileName(fileName);
            assignmentList.setData(file.getBytes());
            assignmentList.setFileSize(file.getSize());
            assignmentList.setFileType(file.getContentType());
            assignmentList.setUploadTime(new Date());
//            assignmentList.setSemester(assignmentList.getSemester());

            assignmentListDao.save(assignmentList);
            return new ResponseEntity("File Uploaded Successfully", HttpStatus.OK);

        }catch (Exception err){
            return new ResponseEntity<>("File not uploaded", HttpStatus.BAD_REQUEST);
        }
    }

What I want to add the semester as well when I upload the file, I put assignmentList.setSemester(assignmentList.getSemester());, But useLess.

Here the Semester is itself an Entity with proper constructors and getter and setters. The semester entity is;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "semester")
public class Semester implements Serializable {

    @Id
    @GeneratedValue (strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int semesterId;

    @Column(name = "semester")
    private int semester;
}

And the Assignment List entity are as follow;

@Entity
@Data
@NoArgsConstructor
@AllArgsConstructor
@Table(name="assignment_list")
public class AssignmentList implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private int fileId;

    @Column(name="file_name", length=512, nullable = false, unique = true)
    private String fileName;

    @Column(name="file_size")
    private Long fileSize;

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

    @Column(name="upload_time")
    private Date uploadTime;

    @Lob
    private byte[] data;

    @OneToOne(cascade = {CascadeType.DETACH}, fetch = FetchType.EAGER   )
    private Semester semester;

// constructor
    public AssignmentList(int fileId, String fileName, Long fileSize, Date uploadTime) {
        this.fileId = fileId;
        this.fileName = fileName;
        this.fileSize = fileSize;
        this.uploadTime = uploadTime;
    }
}

With the following Entity in spring boot when I try to upload file using Reactjs, it will upload it but without the semester_id, The react axios post request is;

const uploadFile = async () => {
        const formData = new FormData();
        formData.append("document", file);
        formData.append("semester", sem);

        await axios
            .post("http://localhost:8080/assignmentlist/uploadfile", formData, {
                headers: {
                    "Content-Type": "multipart/form-data",
                    Accept: "application/json",
                    type: "formData",
                },
            })
            .then(
                function (response) {
                    //handle success
                    console.log(response);
                },
                function (error) {
                    // handle error
                    alert(error.message);
                }
            );
    };

where sem is the value which it get from one of the select box i.e onChange(e => setSem(e.target.value))

I hope I clear my doubt Thanks in Advance :)

Upvotes: 0

Views: 1257

Answers (1)

k-wasilewski
k-wasilewski

Reputation: 4613

Change your controller's method's signature to:

public ResponseEntity<String> uploadData(@RequestParam("document") MultipartFile file, @RequestParam("semester") Semester semester) throws Exception

and then set it like so:

assignmentList.setSemester(semester);

And if that doesn't work, just read the semester as an int and construct the Semester from it yourself.

Upvotes: 1

Related Questions