简体   繁体   中英

Correct way of sending and getting files Spring

Whats the correct way of sending and getting files and save it to a folder?

I am sending a post from Postman with body form-data: 2 keys 'uploadfile' each with one zip.

This code gets only one zip and save it, ignoring the second zip.

How can I implement it to save both files? Also. Should I send 2 files in one key? or each file in separated keys?

@RequestMapping(value = "/api/uploadFile", method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<?> uploadFile(
        @RequestParam("uploadfile") MultipartFile uploadfile) {

    try {


            // Get the filename and build the local file path (be sure that the
            // application have write permissions on such directory)

            String filename = uploadfile.getOriginalFilename();
            String directory = "C://Develop//files";
            String filepath = Paths.get(directory, filename).toString();

            filenameZip = "c:/Develop/files/"+filename;
            directoryZip = "c:/Develop/files";

            // Save the file locally
            BufferedOutputStream stream =
                    new BufferedOutputStream(new FileOutputStream(new File(filepath)));
            stream.write(uploadfile.getBytes());
            stream.close();



    } catch (Exception e) {
        System.out.println(e.getMessage());
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }
       // unzip(filenameZip, directoryZip);
        return new ResponseEntity<>(HttpStatus.OK);
} // method uploadFile

Postman Log:

var data = new FormData();
data.append("uploadfile", "pasta1.zip");
data.append("uploadfile", "pasta2.zip");

var xhr = new XMLHttpRequest();
xhr.withCredentials = true;

xhr.addEventListener("readystatechange", function () {
  if (this.readyState === 4) {
console.log(this.responseText);
  }
});

xhr.open("POST", "http://localhost:8080/api/uploadFile");
xhr.setRequestHeader("authorization", "Basic b3BlcmF0aW9uczpvcGVyYXRpb25z");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.setRequestHeader("postman-token", "e7b6fcae-4a49-de34-ba7c-efd412fb244a");

xhr.send(data);

you can make your service accept array of multipart file then you can send to it as much as you want of files to upload it and here is an exmaple

@RequestMapping(value="/multipleSave", method=RequestMethod.POST )
    public @ResponseBody String multipleSave(@RequestParam("file") MultipartFile[] files){
        String fileName = null;
        String msg = "";
        if (files != null && files.length >0) {
            for(int i =0 ;i< files.length; i++){
                try {
                    fileName = files[i].getOriginalFilename();
                    byte[] bytes = files[i].getBytes();
                    BufferedOutputStream buffStream = 
                            new BufferedOutputStream(new FileOutputStream(new File("F:/cp/" + fileName)));
                    buffStream.write(bytes);
                    buffStream.close();
                    msg += "You have successfully uploaded " + fileName +"<br/>";
                } catch (Exception e) {
                    return "You failed to upload " + fileName + ": " + e.getMessage() +"<br/>";
                }
            }
            return msg;
        } else {
            return "Unable to upload. File is empty.";
        }
    }
} 

and for the key part you can send all files with the same key

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM