已测试:单文件上传

本文详细介绍了如何使用Struts框架进行文件上传操作,包括获取文件流、创建保存路径、生成文件名以及将文件写入服务器的过程,并处理上传过程中的异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) throws Exception {
	
		
		com.cn.struts.form.UploadForm uploadform =(UploadForm)form;
		String context = this.servlet.getServletContext().getRealPath("/");
		System.out.println("context: "+context);
		org.apache.struts.upload.FormFile formfile = uploadform.getFile();   
        java.io.InputStream is = null;   
        java.io.OutputStream os = null; 
        try {   
        	
            is = formfile.getInputStream(); 
            Calendar calendar = new GregorianCalendar();
            Date trialTime = new Date();
            calendar.setTime(trialTime);
            
            //使用当前时间创建保存图片的文件夹
            String timePath = 
           	 calendar.get(
           			 Calendar.YEAR)+"-"+(
           					 calendar.get(
           							 Calendar.MONTH)+1)+"-"+
           							     calendar.get(
           									 Calendar.DAY_OF_MONTH);
            
            System.out.println("timePath: "+timePath);  
            
            
            //如果文件夹不存在,则建立
            String dir=this.getServlet().getServletContext().getRealPath("userUploadPhoto")+"//photo//"+timePath;
            File uploadPath = new File(dir);
           
            if(!uploadPath.exists())
           	 uploadPath.mkdirs();

            //生成上传的文件名
            String ext=formfile.getFileName().split("//.")[1];  
            
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            Date d=new Date();
            sdf.applyPattern("HHmmssSSS");
            
            String filename=sdf.format(d) +(Math.random()+"").substring(2,7);
            filename =filename+ "." + ext; 
            System.out.println("filename===" + filename);
            
            os = new FileOutputStream(dir+"//" + filename); 
            byte[] bytes = new byte[8192];   
            while ((is.read(bytes, 0, 8192)) != -1) {   
                os.write(bytes, 0, 8192);   
            }   
  
            if (os != null)   
                os.close();   
            if (is != null)   
                is.close();                  
            request.setAttribute("msg", "上传成功"); 
        } catch (FileNotFoundException e) {   
            e.printStackTrace();   
            request.setAttribute("msg", "上传失败");   
        } catch (IOException e) {   
            e.printStackTrace();   
            request.setAttribute("msg", "上传失败");   
        }   
  
		return mapping.findForward("msg");
		
		
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值