图片上传到本地服务器

JSP

 
  • 上传
  • 注:图片为.jpg, .jpeg, .png 格式!

JS

  uploadFile({
            subfix: ['jpg', 'jpeg', 'png', 'bmp'],
            url: "/examination/ajax-upload.html",
            subfixTip: "请选择图片!",
            upload: 'upload',
            successCall: function(data) {
                mini.get("picture").setValue(data.savePath);
                $('#personnalPicView').attr('src', contextPath + data.savePath);
                mini.alert(data.flag);
            }
        });

ACTION

@Action("/examination/ajax-upload")
	public void uploadFile() {
		final Map result = Maps.newHashMap();
		// 判断文件大小
		if (this.upload.length() > (5 * 1000 * 1000)) {
			result.put("flag", "fail");
			result.put("msg", "上传文件大小超过限制, ,当前允许的最大文件大小为:5MB");
		} else {
			final String realTempPath = ServletActionContext.getServletContext().getRealPath(BASE_ATTACH_DIR);
			final String fileFix = this.uploadFileName.substring(this.uploadFileName.lastIndexOf("."));
			final String fileName = this.uploadFileName.substring(0, this.uploadFileName.lastIndexOf("."));
			final String savePath;
			if (StringUtils.isNotBlank(this.dir)) {
				savePath = FILE_SEPARATOR + this.dir + FILE_SEPARATOR + fileName + "_" + new Date().getTime() + fileFix;
				final File saveDirFile = new File(realTempPath + FILE_SEPARATOR + this.dir);
				if (!saveDirFile.exists()) {
					saveDirFile.mkdirs();
				}
			} else {
				savePath = FILE_SEPARATOR + new Date().getTime() + fileFix;
			}
			try {
				FileUtils.copyFile(this.upload, new File(realTempPath + savePath));
				result.put("flag", "上传成功!");
				result.put("savePath", BASE_ATTACH_DIR + savePath);
				result.put("fileName", this.getUploadFileName());
			} catch (final IOException e) {
				e.printStackTrace();
				result.put("flag", "fail");
				result.put("msg", "程序有误,联系管理员");
			}
		}

		sendResponseMsg(new Gson().toJson(result));
	}

存库

final String realTempPath = ServletActionContext.getServletContext().getRealPath("/");
			final String realTempPat1 = ServletActionContext.getServletContext().getRealPath(BASE_ATTACH_DIR);
			final String fileFix = doctorInfoFormVo.getPicture()
					.substring(doctorInfoFormVo.getPicture().lastIndexOf("."));
			File oldFile = new File(realTempPath + doctorInfoFormVo.getPicture());
			File newFile = new File(realTempPat1 + File.separator + doctorInfoFormVo.getZjhm() + fileFix);
//查到文件有相同的名字的文件删除掉
			if(newFile.exists()){
				newFile.delete();
			};
//修改已经上传的文件名字
			if (oldFile.renameTo(newFile)) {
				System.out.println("修改成功!");
			} else {
				System.out.println("修改失败");
			}
			String picurl=(BASE_ATTACH_DIR+FILE_SEPARATOR+doctorInfoFormVo.getZjhm() + fileFix);
			doctorInfoFormVo.setPicture(picurl);
			this.straightService.saveOrUpdate(doctorInfoFormVo);

 

你可能感兴趣的:(java)