JSP page code:
<form name= "form" id= "form" method= "POST" >
<span class= "Title-span" > Equipment Pictures </span>
<input type= "File" id= "ImageFile"/>
<input type= "button" value= "Upload picture" onclick= "saveimg (' Save Picture Path ')"/>
<div name= "Result" id= "result" >
<!--here to show picture results--
</div>
</form>
JS as follows:
/***** Reading Pictures start******/
var imgfile = "";
$ ("#imagefile"). Live (' Change ', function () {
if (typeof filereader== ' undifined ') {//Determine if the browser supports FileReader
var Result=document.getelementbyid ("result");
Result.innerhtml= "<p> Sorry, your browser does not support filereader</p>";
return false;
}
Imgfile = document.getElementById ("ImageFile"). Files[0];
if (!/image\/\w+/.test (Imgfile.type)) {//To determine if a picture file was obtained
Alert ("Please select the correct image file");
var obj = document.getElementById (' ImageFile ');
obj.outerhtml=obj.outerhtml;
return false;
}
if (imgfile! = undefined) {
var reader=new filereader ();
Reader.readasdataurl (Imgfile);
Reader.onload=function (e) {
var Result=document.getelementbyid ("result");
Result.innerhtml= '
}
}
});
/***** Reading Pictures end******/
/***** Image Upload Method ******/
function saveimg(URL) {
var formData = new FormData (); Create a Formdata form data object
Formdata.append ("file", Imgfile); File Object
$.ajax ({
Url:url,
Type: ' Post ',
Data:formdata,
Processdata:false,
Contenttype:false,
Cache:false,
Success:function (str) {
alert (str);
},
Error:function (JQXHR, Textstatus, Errorthrown) {
alert (Jqxhr.responsetext);
}
});
}
/***** Background Code ******/
@RequestMapping (value= "/save", produces= "Text/plain;charset=utf-8")
@ResponseBody
Public String saveequipment (equipment equipment,httpservletrequest request) throws exception{
/** first instantiate a file parser */
Commonsmultipartresolver comultipartresolver = new Commonsmultipartresolver (Request.getsession (). GetServletContext ());
/** to determine if there are file uploads in request requests */
if (Comultipartresolver.ismultipart (request)) {
/** Conversion request*/
Multiparthttpservletrequest multirequest = (multiparthttpservletrequest) request;
/** Get File */
Multipartfile file = multirequest.getfile ("file");
if (file! = null) {
InputStream is = File.getinputstream ();
byte[] nb = new byte[is.available ()];
Is.read (NB);
Is.close ();
Base64encoder encoder = new Base64encoder ();
/** set the image to Base64 */
String encode = Encoder.encode (NB). Trim ();
Set picture Properties
Equipment.seticon (encode);
}else {
System.out.println ("--------file-------not selected");
}
Call the persistence layer method to save to the database
result = Equipmentservice.insert (equipment);
return result? "Upload succeeded": "Upload Failed"
}
}
Javaweb Project JS image uploaded to Oracle to base64 database