0

I am trying to download csv file and wanted to upload that same csv file into my server location path using Spring MVC and through Ajax Post request on executing my application.

From the below code, I can able to download my csv file on running my application, but it is not uploading into my server location path at the same time or simultaneously on executing of the application, I am not sure why it is not uploading. Please help me to upload my file at my given path. Thanks !

js:

function download_csv(csv, filename) {
//filename = test.csv
//csv = "testname,testid
         hello,10"

    var csvFile;
    var downloadLink;
// CSV FILE
csvFile = new Blob([csv], {type: "text/csv"}); //[object Blob] 

// Download link
downloadLink = document.createElement("a");

// File name
downloadLink.download = filename;

var formData = new FormData(csvFile);
console.log(formData);//FormData {} 

    $.ajax({
            url: "/uploadFile",
            type: "POST",
            //data: filename,
            // data: new FormData(csvFile),
            data: formData,
            //  enctype: 'multipart/form-data',
            processData: false,
            contentType: false,
            cache: false,
            success: function (data) {
            // Handle upload success
                $("#upload-file-message").text("File succesfully uploaded");
                                    },
                                    error: function (errordata) {
                                        console.log("error: "+errordata);//[object Object]
                                        console.log("error data: "+JSON.stringify(errordata));

                                      }
            });//$.ajax() 

    // We have to create a link to the file
    downloadLink.href = window.URL.createObjectURL(csvFile);

    // Make sure that the link is not displayed
    downloadLink.style.display = "none";

    // Add the link to your DOM
    document.body.appendChild(downloadLink);

    // Lanzamos
    downloadLink.click();

}

controller:

@Controller
public class MainController {

@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
  @ResponseBody

  public ResponseEntity<?> uploadFile(
          @RequestParam("filename") MultipartFile uploadfile) {

    try {
      // Get the filename and build the local file path
      String filename = uploadfile.getOriginalFilename();
      String directory = env.getProperty("paths.uploadedFiles");
      String filepath = Paths.get(directory, filename).toString(); 
      // 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);
    }

    return new ResponseEntity<>(HttpStatus.OK);
  } 

} 

application.resources:

paths.uploadedFiles = /resources/test/

POST http://localhost:8000/uploadFile 400 (Bad Request)

error data: {"readyState":4,"responseText":"{\"timestamp\":1511523835282,\"status\":400,\"error\":\"Bad Request\",\"exception\":\"org.springframework.web.bind.MissingServletRequestParameterException\",\"message\":\"Required MultipartFile parameter 'filename' is not present\",\"path\":\"/uploadFile\"}","responseJSON":{"timestamp":1511523835282,"status":400,"error":"Bad Request","exception":"org.springframework.web.bind.MissingServletRequestParameterException","message":"Required MultipartFile parameter 'filename' is not present","path":"/uploadFile"},"status":400,"statusText":"Bad Request"}

Guna
  • 138
  • 4
  • 17
  • can you able to get your csv file in variable formData ? – Jay Nov 24 '17 at 12:37
  • @Jay, thanks for your reply, it is giving like: FormData {} – Guna Nov 24 '17 at 12:40
  • 1
    can you try with `XMLHTTPRequest` ? – Jay Nov 24 '17 at 12:42
  • @Jay, i don't know who to try or check with XMLHTTPRequest, I am new to this all actually. – Guna Nov 24 '17 at 12:44
  • 1
    please ref use [XmlHttpRequest](https://stackoverflow.com/questions/6211145/upload-file-with-ajax-xmlhttprequest) – Jay Nov 24 '17 at 12:47
  • @Jay, i have tried like this, but still same error: var url='/uploadFile', xhr = new XMLHttpRequest(); var file=filename; xhr.file=file; xhr.open('post', url, true); // xhr.setRequestHeader("Content-Type","multipart/form-data"); var formData = new FormData(); formData.append("filename", file); xhr.send(formData); – Guna Nov 24 '17 at 13:03
  • @Jay, yes, i got it now: i did in the above code like: formData.append("filename",csvFile,filename); Thanks for your inputs ! – Guna Nov 24 '17 at 13:21
  • 1
    The problem is you are missing the parameter called filename in the request itself. So if you are using something like postman just set the paraeter name to 'filename' and try to send the request and it will work – Amr Alaa Nov 24 '17 at 14:39

0 Answers0