昨天,我的朋友需要上传一张图片。他问我,我以前写过一个。我想其他人可能需要这个,所以现在我把它整理出来供你参考。我希望这对你有帮助。
<form id="orgLogoAddrUploadForm" method="post" target="upload_result" action="${webRoot}/articlePush/uploadImage" class="form-horizontal col-sm-12 form" style="margin-left: 0; display: none;" enctype="Multipart/form-data"><p class="form-group" style="margin-bottom: 0;"><p id="thumbnailUploadContainer" class="col-sm-10"><span style="font-weight: bolder;">图片上传:</span> <input id="orgLogoAddrImageFile" name="imageFile" type="file" class="form- control" style="width: 180px; display: inline;" /> <button id="uploadButton" class="btn btn-primary" type="button">上传图片 </button> <span style="color:red;">*</span> </p> </p></form>
不需要介绍每个标签的具体功能。如果你不明白,你可以自己百度!
前端(js)
// 图片上传按钮$(”#uploadButton").on("click", function() {var image = $("#orgLogoAddrImageFile").val();if (image==null || image.length<=0) {alert(“请选择上传的图片!");return;}$("#orgLogoAddrUploadForm").submit(); });
后端(springmvc+mybatis)
@LoggerAnno(funcName="上传新闻缩略图"@RequestMapping("/uploadArticleImage")public String uploadArticleImage(HttpServletRequest request, Model model) {MultipartRequest mrequest = (MultipartRequest) request;MultipartFile mfile = mrequest.getFile("imageFile"); // 判断文件是否为空if (mfile == null || mfile.getSize() == 0) {BaseModel result = new BaseModel();result.setSuccess(false);result.setMessage(“请选择上传文件”;try {model.addAttribute("uploadResult", JSONUtils.toString(result));} catch (IOException e) {logger.error("", e);throw new RuntimeException();} //这是一个页面地址,因为我设置了静态变量,这里就不展示return了 UPLOAD_RESULT_PAGE;}//long imgSize=1000; ///默许200Klong imgSize = 2* 1024 * 1024;///默许2MString resultMsg = "2M";// 判断文件大小是否超过设定值if (mfile.getSize() > imgSize) {BaseModel result = new BaseModel();result.setSuccess(false);result.setMessage(“文件大小不得超过”+resultMsg+", 请重新上传”);try {model.addAttribute("uploadResult", JSONUtils.toString(result));} catch (IOException e) {logger.error("", e);throw new RuntimeException();}return UPLOAD_RESULT_PAGE;}try {// Stringg后缀文件 postFix = SystemFileUtils.getFilePostFix(mfile.getOriginalFilename());// 上传相对路径, 按月创建文件夹,根据自己的实际情况设置Dateee date = new Date();DateTime dt = new DateTime(date);int year = dt.getYear(); // 年int month = dt.getMonthOfYear(); // 月// String文件名 fileName = SystemStringUtils.getUUID() + postFix;String uploadPath = this.systemConfigs.getArticleThumbnailUploadPath() + "/" + year;if(month<10){uploadPath += "0";}uploadPath += month +"/" + fileName;// 保存路径 在此填写服务器地址+tomcat下指定保存图片的文件夹String savePath = this.systemConfigs.getUploadSaveBasePath() + uploadPath;// 判断文件夹是否存在,如果不存在,新建的File就不存在了 saveFile = new File(savePath);if (!saveFile.getParentFile().exists()) {saveFile.getParentFile().mkdirs();}Image srcImg=javax.imageio.ImageIO.read(mfile.getInputStream());// 保存图片文件 InputStream inputStream = mfile.getInputStream(); FileUtils.copyInputStreamToFile(inputStream, saveFile); // 设置缩略图入库路径String accessPath = this.systemConfigs.getUploadAccessBasePath() + uploadPath;// BaseModel返回数据 result = new BaseModel();Map<String, Object> data = new HashMap<String, Object>();data.put("type", "image");data.put("accessPath", accessPath);result.setData(data);model.addAttribute("uploadResult", JSONUtils.toString(result));return UPLOAD_RESULT_PAGE;} catch (Exception e) {logger.error("", e);BaseModel result = new BaseModel();result.setSuccess(false);result.setMessage(“上传失败”);try {model.addAttribute("uploadResult", JSONUtils.toString(result));} catch (IOException e2) {logger.error("", e2);throw new RuntimeException();}///这是返回视图(jsp页面)return UPLOAD_RESULT_PAGE;}}