I have been stuck on this problem for the last couple of days and no other posts have been helpful. I'm trying to upload a file on a HTML form which looks like this (it contains other fields):
<input type="text" id="prenom" name="fname" placeholder="Prenom"><br><br>
<input type="text" id="nom" name="fname" placeholder="Nom"><br><br>
<input type="email" id="mail" name="fname" placeholder="Adresse mail"><br><br>
<input type="file" id="file" name="file" />
</form>
<br><button id="bouton-inscription" >s'inscrire</button>```
and then upload it to using Ajax through a FormData:
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: './upload',
cache: false,
processData: false,
contentType: false,
method: 'POST',
data: formData,
dataType: 'json'
})
Then, server-side, I want to retrieve the file and save it using a httpServlet, I'm using this code I "adapted" from Oracle docs:
@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = "C:\\Users\\me\\Desktop";
final Part filePart = request.getPart("file");
final String fileName = "myFile";
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
But I'm getting a an error in the Ajax call (I'm handling the other fields with another ajax call to another servlet which works just fine since they're text fields).
I feel like the problem must be server-side because the code I'm using client-side I've seen everywhere.
Any hints would be much appreciated!
Thanks!
Edit: Actually with this code the file is saved correctly but there is still an Ajax error
.fail(function (error) { console.log('Error', error); alert("Erreur lors de l'appel AJAX"); })After the ajax call, and this code is called - saadovskyconsole.log('Error', error);gives in console ? - Swati