Java后台处理文件上传

前端代码不展示,通过ajax请求后台地址,完成上传文件

//文件上传
	public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {        
		File targetFile = new File(filePath); 
		if (!targetFile.exists()) {
		   targetFile.mkdirs();    
		}        
		FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);
		out.write(file);      
		out.flush();   
		out.close(); 
	}
		
		//处理文件上传
		@Log("文件上传")
	  	@RequestMapping(value = "uploadImg", method = RequestMethod.POST)
	  	public R uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) throws JSONException {        
	  	    String contentType = file.getContentType(); 
	  	    System.out.println(contentType);
	  		String fileName = System.currentTimeMillis()+file.getOriginalFilename();	//随机生成文件名
	  		System.out.println(fileName);
	  			int  code=0;
	  		String filePath = "D:img";	//上传到本地的路径,D盘下的img文件夹
	  		if (file.isEmpty()) {   
	  			code=1;
	  			fileName="";
	  		}        
	  		try {  
	  		   uploadFile(file.getBytes(), filePath, fileName);  
	  		   code=0;
	  		} catch (Exception e) {  
	  		// TODO: handle exception        
	  		}  
	  		//返回json
	  	    return R.ok().put("code", code).put("fileName", "/imctemp-rainy/"+fileName);  //处理成功返回的结果,
	  	    data.code=0		//表示上传成功  
	  	    data.fileName   //返回上传的文件名,例:/imctemp-rainy/+文件名
	  	}
发布了26 篇原创文章 · 获赞 32 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_45736927/article/details/104632816