Ajax上传图片

一、后端接收图片代码

@Controller
@RequestMapping(value = "/io", produces = MediaType.APPLICATION_JSON_VALUE)
public class IoController {
	/**
	 * 上传文件通用接口
	 * 
	 * @param file
	 *            文件
	 * @param request
	 * @return
	 * @throws IllegalStateException
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	@ResponseStatus(HttpStatus.CREATED)
	@ResponseBody
	public BaseVO uploadFile(MultipartFile file,String remark,HttpServletRequest request)
			throws IllegalStateException, IOException {
		//绝对根路径
		String realPath=request.getServletContext().getRealPath("/"); 
		System.out.println(realPath);
		if (file != null) {

			// 保存文件
			String myFileName = file.getOriginalFilename();
			// 如果名称不为“”,说明该文件存在,否则说明该文件不存在
			if (myFileName.trim() != "") {
				// 重命名上传后的文件名
				String fileName = file.getOriginalFilename();
				// 定义上传路径
				String relativePath="uploads"+File.separator+DateUtils.getYMD();
				File pathFile = new File(realPath+relativePath);
				if (!pathFile.exists()) {
					pathFile.mkdirs();
				}
				String path = pathFile +File.separator+ fileName;
				File localFile = new File(path);
				file.transferTo(localFile);
				return BaseVO.getSuccess(relativePath+File.separator+ fileName);
			}

		}
		return BaseVO.getSuccess("成功上传文件");
	}
}

二、前端HTML代码 (upload.html)




上传文件




  






	

你可能感兴趣的:(javaWeb知识)