Preface
Want to implement a function: users click the Upload button, select the picture after. The picture appears on a pop-up box, and you can crop the picture. The cropped picture appears on the page. Submit the form to upload the picture. Encounter problem browser security settings do not allow users to obtain uploaded image path, the actual acquisition is c:\fakepath\a.jpg (assuming the picture is the a.jpg under C disk) Ajax How to upload pictures asynchronously. Canvas picture Cropped when the width is different (originally wanted to draw 100x100 picture, the results on the canvas display 100x50) canvas picture how to upload. Problem Resolution Select the picture, trigger the input of the onchange event: send an asynchronous request to upload the picture, return the name of the picture, and then play the frame, the picture displayed. The form is encapsulated as Formdata type, Ajax can be set up, specific Baidu has said. Set Canvas width I use the style:width:100px;height:100px, and then directly write canvas properties width=100px height=100px, the problem is solved. Specific reasons Baidu has said. Gets the canvas picture stream (which is actually a string), and the form submits the picture stream. The background uses BASE64 to parse the picture stream into a byte array, and then create an input stream based on the byte array, and with the input stream, you can write a picture. part of the code
<!--image upload, openphotocut function is to upload pictures asynchronously, display pictures and crop--> <form "id=" class
= "Form-horizontal" role= "form" enctype= "Multipart/form-data" > <div class= "Form-group namediv" > <label class= "col-sm-2" for= "photo" style= "font-size:15px"; ><span style= "color:red;" > </span> Food pictures </label> <div class= "col-sm-6" > <input Type= "file" class= "photo" id= "photo" name= "photo" onchange= "Openphotocut" (); "/> </div> </ Div> </form>
Open Picture crop box function openphotocut () {//Ajax upload image key var formData = new FormData ($ ("#uploadForm")); var fileName;
Upload file name//Add the uploaded picture to the form formdata.append ("Photo", $ (". Photo"). Get (0). Files[0]); Upload an $.ajax picture ({type: POST), url: "${pagecontext.request.contextpath}/business/prod Uct/getfilelocationajax ", Async:false, Data:formdata,//The following two lines do not write may be an error con
Tenttype:false, Processdata:false, success:function (Result) {//Get Picture name
FileName = result;
alert (fileName);
}
}); Here is the use of Layer Bomb box plug-ins, pop-up picture cropping box, display uploaded pictures, and to cut Layer.open ({title: ' Picture cropping ', type:1, skin: ' Layui-layer-rim ',//plus border area: [' 600px ', ' 500px '],//wide/high/here is purely HTML content, Cutandshow's function is to delete the picture just uploaded, then cut
The picture appears on the canvas and saves the picture stream in input. ContenT: ' ' + ' <butt On class= "btn btn-primary" style= margin:20px; "onclick=" cutandshow (\ ' + fileName + ' \ '); " > Crop </button> ' + ' x axis: <input type= "text" readonly id= "x" name= "x" value= "0" style= "width:50px;"/&G T ' + ' Y-axis: <input type= "text" readonly id= "y" name= "y" value= "0" style= "width:50px;"/> ' + ' Length: <input type= "text" readonly id= "W" name= "W" value= "0" style= "width:50px;"/> ' + ' width: <input type=
"Text" readonly id= "H" name= "H" value= "0" style= width:50px; "/>"}); Crop the plug-in $ ("#prephoto").
Jcrop ({minsize: [80, 80],//min size aspectratio:1,//equal width and height onselect:updatecoords
});
//Timely update crop area coordinates and dimensions function Updatecoords (c) {$ (' #x '). Val (c.x);
$ (' #y '). Val (C.Y);
$ (' #w '). Val (C.W); $ (' #h '). Val (c.h);
};
Crop the picture and display it in the canvas function cutandshow (fileName) {//delete the cropped picture $.ajax ({type: POST), URL: "${pagecontext.request.contextpath}/business/product/deleteimageajax", Async:false, data
: {"filename": filename}, Success:function (Result) {}});
var x = $ ("#x"). Val ();
var y = $ ("#y"). Val ();
var w = $ ("#w"). Val ();
var h = $ ("#h"). Val ();
if (x = = 0 | | | y = = 0 | | | w = = 0 | | h = = 0) {alert ("Please crop image");
var img = document.getElementById ("Prephoto");
var C=document.getelementbyid ("Oldconvas");
var ctx = C.getcontext ("2d"); Ctx.drawimage (IMG, x, y, W, h,0,0,100,100); Picture, size 100x100 var newimg = C.todataurl ("Image/jpeg"); Get Picture Stream $ (". Photostream"). Val (newimg); Store the picture character stream in input layer.closeall (); Close All Windows}
<!--this is another form for uploading pictures and other content--> <form class= "form-horizontal" role= "form" method= "POST" onsubmit= "re Turn validate (); "Action= ${pagecontext.request.contextpath}/business/product/add.action" > <!--cropped pictures --> <div class= "Form-group namediv" > <label class= "col-sm-2" for= "name" style= "fon t-size:15px; " ></label> <div class= "col-sm-6" > <span class= "Text Text-danger" > on Transfer picture requirements: Format jpg/jpeg/png/gif/bmp, size <=2m, size <=500x500, after cropping picture size for 100x100</span> <div style = "width:100px; height:100px; border:1px solid black; " ><canvas id= "Oldconvas" width= "100px" height= "100px" ></canvas></div> <input ty Pe= "hidden" class= "Photostream" id= "Photostream" name= "Photostream"/> </div> </di V> <!--Other forms content, do not write--> </form>
/** * Upload the picture asynchronously and return the picture name * @param model * @param request * @param response * @param file uploaded pictures * @throws Exception * * * @RequestMapping (value= "Getfilelocationajax", method=requestmethod.post) public void g Etfilelocationajax (model model, HttpServletRequest request, httpservletresponse response, @RequestParam ("Photo") Commonsmultipartfile file) throws Exception {if (!file.isempty ()) {InputStream in = File.getinputst
Ream (); String fileName = saveimage (request, in);
Call Save Picture Method//Save picture name, easy to cut after delete model.addattribute ("filename", filename); Response.setcontenttype ("Html/text;
Charset=utf-8 ");
PrintWriter writer = Response.getwriter ();
Writer.print (FileName); /** * Save picture to upload path * @param request * @param in Picture input stream * @throws Exception * @return return Back to filename/public String saveimage (httpservletrequest request, InputstreAM in) throws Exception {String fileName = Uuidutils.getuuid () + ". jpg"; Random filename String savepath = request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/uploads") + "/";
Get save path File F = new file (Savepath);
if (!f.exists ()) {f.mkdirs ();
FileOutputStream fos = new FileOutputStream (Savepath + fileName);
int b = 0;
while ((b = in.read ())!=-1) {fos.write (b);
} fos.close ();
In.close ();
return fileName; }
/** * Asynchronous deletion of uploaded files * @param response * @param request * @param filename filename * @throws Exception */@RequestMapping (value= "/deleteimageajax") public void Deleteimageajax (HttpServlet
Request request, String FileName) throws Exception {System.out.println ("Picture name:" + filename); String Savepath = Request.getsession (). Getservletcontext (). Getrealpath ("/web-inf/uploads") + "/";
Get save path File = new file (Savepath + fileName);
Boolean flag = false;
if (!file.exists ()) {System.out.println ("file does not exist, cannot be deleted");
else {if (File.isfile ()) {flag = File.delete (); }
}
}
/**
* Save pictures according to Picture stream *
@param request
* @param data stream
* @throws Exception
* @return Picture name
* * Public String Saveimagebystrem (httpservletrequest request, String data) throws Exception {
Base64 base64 = new Base64 ( );
Get picture stream, actual picture data starting from Data:image/jpeg;base64
byte[] b = base64.decodebase64 (Data.substring ("DATA:IMAGE/JPEG; Base64, ". Length ());
InputStream in = new Bytearrayinputstream (b);
String fileName = saveimage (request, in); Save picture return
fileName;
}
Experience
Front-end plug-ins are flying, often causing the choice of difficult disease. Encounter a plugin, feel difficult to give up, change a plug-in, or too troublesome, and another, the result entered a dead loop. Not only waste time, but also affect the mood. Plug-ins are to be easily developed, not to toss.