【Java】图片上传

图片上传功能在Controller层实现的完整方法如下:

方法一:

@RequestMapping("toUploadImage.do")  
       public String upload(@RequestParam MultipartFile uploadfile,   
               HttpServletRequest request, HttpServletResponse response,String tid) {  
        //获取输入的文件名  
           String fileName = uploadfile.getOriginalFilename();  
           if (StringUtils.isEmpty(fileName)) {  
               System.out.println("未上传文件名为空");  
           }  
           //获取路径  
           String tempPath = request.getSession().getServletContext().getRealPath("/")  
                   + "upload\\ysdwanimal";  
           File dir = new File(tempPath);           
           if (!tempPath.endsWith(File.separator)) {  
               tempPath = tempPath + File.separator;  
           }  
           if (!dir.exists()) {  
               dir.mkdirs();  
           }             
           System.out.println(tempPath+fileName);  
           //检查是否重复上传  
           HmImages hmImage = HmImageService.getEntryById(tid);  
           if(hmImage == null){  
            return "uploadfail";  
           }  
           //重写数据库储存路径  
           String lj=request.getScheme() + "://" + request.getServerName()  
                + ":" + request.getServerPort() + "/whzhly/upload/ysdwanimal/"+id+".jpg";  
           //保存路径  
           ysdwAnimal.setLujing(lj);  
           ysdwAnimalService.saveOrUpdateYsdwAnimal(ysdwAnimal);  
           //获取完整的图片名  
           String newFile = tempPath + id+".jpg";           
           File file = new File(newFile);  
           //图片复制到指定文件夹中,实现路径  
           try {  
               FileCopyUtils.copy(uploadfile.getBytes(), file);  
                 
               System.out.println("成功上传");  
           } catch (IOException e) {  
               e.printStackTrace();  
               return "uploadfail";  
           }   
           return "uploadsuccess";  
       }  


方法二:

@RequestMapping("/toUpLoadHmImage.do")
	public @ResponseBody String toUpLoadHmImage(HttpServletRequest request,
			HttpServletResponse response,ModelMap model){
		//获取到项目名称
		String projectName =  request.getContextPath();
		//得到上传文件的保存目录,将上传的文件存放于WEB-INF目录下,不允许外界直接访问,保证上传文件的安全
		String savePath =  request.getServletContext().getRealPath("/WEB-INF/primary/images");
		File file = new File(savePath);
		//判断上传文件的保存目录是否存在
		if(!file.exists() && !file.isDirectory()){
			//不存在,则创建目录
			file.mkdir();
		}
		//消息提示
		String message = "";
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			//创建一个文件上传解析器
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setHeaderEncoding("utf-8");
			//设置上传的文件总的大小不能超过5M  
			upload.setSizeMax(1024 * 1024 * 5);
			//判断提交上来的数据是否是上传表单的数据
			if(!ServletFileUpload.isMultipartContent(request)){
				return message;
			}
			/*
			 * 使用ServletFileUpload解析器解析上传数据,
			 * 解析结果返回的是一个List<FileItem>集合
			 */
			List<FileItem> list = upload.parseRequest(request);
			for(FileItem item : list){
				if(item.isFormField()){//如果fileitem中封装的是普通输入项的数据
					String itemName = item.getFieldName();
					String itemValue = item.getString("utf-8");
					System.out.println(itemName + "=" + itemValue);
				}else {//如果fileitem中封装的是上传文件
					//得到上传的文件名称
					String fileName =item.getName(); 
					System.out.println("fileName=" + fileName);
					if(fileName == null || fileName.trim().equals("")){
						continue;
					}
					//处理获取到的上传文件的文件名的路径部分,只保留文件名部分
					fileName = fileName.substring(fileName.lastIndexOf("\\")+1);
					//获取item中的上传文件的输入流
					InputStream inputStream = item.getInputStream();
					//创建一个文件输出流
					FileOutputStream outputStream = new FileOutputStream(savePath+"\\"+fileName);
					//创建一个缓冲区
					byte buffer[] = new byte[1024];
					//判断输入流中的数据是否已经读完的标识
					int len = 0;
					//循环将输入流读入到缓冲区当中,(len=in.read(buffer))>0就表示in里面还有数据
					while((len=inputStream.read(buffer))>0){
					//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
						outputStream.write(buffer, 0, len);
					}
					//关闭输入流
					inputStream.close();
					//关闭输出流
					outputStream.close();
					//删除处理文件上传时生成的临时文件
					item.delete();
					message = "文件上传成功";
				}
			}
		} catch (Exception e) {
			 message= "文件上传失败!";
			 e.printStackTrace();
		}
		return message;
		
	}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张思全

实践,方能出真知!打赏博主吧!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值