// Controller Code
@RequestMapping(value = “admin/image/product/{id}/{imagetype}/upload”, method = RequestMethod.POST)
public String handleFileUpload(
@PathVariable(“id”) int id, @PathVariable(“imagetype”) String imagetype,
@RequestParam(value=”file”, required=true) MultipartFile file)
{
if (!file.isEmpty()) {
try {
String filePath = Constants.IMAGE_PATH + “/items/” + id +”/” + imagetype;
String fileName = file.getOriginalFilename(); // Finds the files Original filename
String fileType = fileName.split(“\\.”)[1]; // Identifies fileType
File dir = new File( filePath );
// Creates the upload path if not exists.
if ( !dir.exists() ) {
if ( dir.mkdirs() ) {
LOGGER_.info(“Directory created successfully “);
} else {
LOGGER_.info(“Directory creation failed”);
}
}
// saves the file uloaded.
File uploadingFilePath = new File ( dir.getAbsoluteFile() + “/” + id + “.” + fileType );
BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(uploadingFilePath));
byte[] bytes = file.getBytes();
stream.write(bytes);
stream.close();
return “OK:” + uploadingFilePath.getAbsolutePath();
} catch (Exception e) {
return “FAIL:” + e.getMessage();
}
} else {
return “FAIL:No Image”;
}
}
Front END call:
JS:
function saveProfileImage() {
var formData = new FormData();
formData.append(‘file’, $(‘input[type=file]’)[0].files[0]);
console.log(“form data ” + formData);
$.ajax({
url : “${ADMIN_URL_PREFIX}/admin/image/product/${param[‘productid’]}/product-list/upload”,
data : formData,
processData : false,
contentType : false,
type : ‘POST’,
success : function(data) {
var response = data.split(“:”);
if ( response[0] == “OK”) {
$(“#errorbox”).html (“Uploaded Image Saved successfully”);
$(“#product_image”).attr(“src”, response[1]);
} else {
$(“#errorbox”).html (“Uploaded Image not Saved successfully”);
}
},
error : function(err) {
$(“#errorbox”).html (“err”);
}
});
}
JSP / HTML
<input type=”file” name=”file” id=”fileChooser” multiple required />
<button type=”button” onclick=”saveProfileImage()” id=”upload” multiple size=”5″ class=”btn-u”>Upload Image</button>
<p id=”errorbox”></p>
