Upload and preview java images. jQuery plug-in AjaxFileUpload is used at the front end, And FileUtils. copyFile is used at the backend.
Personal notes for future use.
Table body code:
View images
Js Code (remember to introduce the jquery library and ajaxfileupload Library ):
// Upload the file ID function fileUpload (uploadFileId, filePathId, imgId) {var imp = document. getElementById (uploadFileId); if (imp = null | imp = "" | imp = undefined) {alert ('select A file'); return;} $. ajaxFileUpload ({url: ct + "uploadFile. do ", secureuri: false, fileElementId: uploadFileId, dataType: 'multipart/form-data', success: function (data, status) {var json = eval ('+ data +'); if (json. msg = "1") {alert ("uploaded successfully "); $ ('#' + FilePathId ). val (json. path); $ ('#' + imgId ). attr ("src", eTrade. ctx + "/upload/" + json. path) ;}else {alert ("File Upload Failed") ;}, error: function (data, status, e) {alert (e );}});} function viewPic (dialogId, imgId, fileId) {$ ("#" + dialogId ). dialog ({height: 350, width: 600, buttons: {"cancel": function () {$ ("#" + imgId ). attr ("src", ""); $ (this ). dialog ("close") ;}}, close: function () {$ ("#" + imgId ). attr ("src ","") ;}}); If ($ ("#" + fileId ). val () = "") {return ;}$ ("#" + imgId ). attr ("src", ct + "/toView. do? Attachment = "+ $ (" # "+ fileId). val ());}
Background Code (the uploadFile name must be the same as the frontend name = "uploadFile" value ):
Private File uploadFile; public File getUploadFile () {return uploadFile;} public void setUploadFile (File uploadFile) {this. uploadFile = uploadFile;} @ Action (value = "uploadFile", results = {@ Result (name = "success", type = "json", params = {"ignoreHierarchy ", "false", "contentType", "text/html", "root", "dataMap"})} public String uploadFile () {try {String UPLOAD_PATH = ServletActionContext. GetServletContext (). getRealPath ("/upload/"); String randomName = UUID. randomUUID (). toString () + ". jpg"; if (uploadFile! = Null) {File storageFile = new File (UPLOAD_PATH + "/" + randomName); FileUtils. copyFile (uploadFile, storageFile);} dataMap. put ("msg", 1); dataMap. put ("path", randomName); // File ID} catch (Exception e) {logger. error ("", e); dataMap. put ("msg", 0);} return SUCCESS ;}
The above code may be incomplete, but the general idea is as follows, just to facilitate later use.