0
my html code:
<input type="file" id="myFile" name="files[]">

ajax code:
var file = document.getElementById('myFile').files[0].name;
var poststr = 'file='+ escape(file)+'&key='+ escape('project_creation');
makePOSTRequest('controller', poststr,'bdy');

Controller:
if (param.equals("project_creation")) {
    param="project_creation";
    int proj_id = hlp.createProject(req,emp_id);
}

while retrieving through request i am getting only the file name. I need to save the file in local path.

Any help will be appreciated. Thanks in advance.

Rabindra
  • 101
  • 1
  • 4
  • 13
  • Instead of checking `project_creation` in Controller, check for `key` because you are sending the value of `project_creation` is sent through `key`. – kk. Jun 14 '17 at 10:48

2 Answers2

0

Have you used Form? so don't forgot to add attribute enctype="multipart/form-data" into form element.

Ansari Maksud
  • 316
  • 2
  • 5
  • 20
  • No, I haven't used Form. All defined in div only. – Rabindra Jun 14 '17 at 11:11
  • 2
    Okay, So you have to read files content also, `var file = document.getElementById('myFile').files[0].name`, this code return only file name, `new FileReader()` function return file content, Let me answer again. so it will helpful. – Ansari Maksud Jun 14 '17 at 12:02
0

Your code only working to read file name, if you want to save file, so you have to send file content in ajax call, and save by server coding, please check the below code that helpful to read file content,

var myFunction = function(){
var input = document.getElementById('myFile');
var reader = new FileReader();
reader.onload = function(){
    var dataURL = reader.result;

    console.log(input.files[0]); //Files property, size, name, type
    console.log(dataURL); //File content in base64

    var fileName = input.files[0].name; //File Name
    var poststr = 'file='+ escape(dataURL)+'filename='+ escape(fileName)+'&key='+ escape('project_creation'); //Prepare URL params
    makePOSTRequest('controller', poststr,'bdy');
};
reader.readAsDataURL(input.files[0]);

}

I have face the same issue against file read in javascript, and this code working for me. I have face same issue against file read in javascript, and this code working for me.

Ansari Maksud
  • 316
  • 2
  • 5
  • 20
  • 1
    Read files using `new FileReader();` and read property of file using `input.files[0]` – Binary Brackets Jun 14 '17 at 12:11
  • 1
    Thanks Maqsud...it realy works....but can you please let me know how can I check this file in controller and save it in server/local path??? – Rabindra Jun 15 '17 at 07:19
  • Rabindra, Using `new FileReader();` you can send file content, Please refer mention link that helpful to read file in server side in JAVA [https://stackoverflow.com/questions/23979842/convert-base64-string-to-image](https://stackoverflow.com/questions/23979842/convert-base64-string-to-image) – Ansari Maksud Jun 15 '17 at 08:23