Struts2基本读写法上传文件

2019-04-15 16:32发布

String savepath = ServletActionContext.getServletContext().getRealPath("/upload"); System.out.println(savepath); try { File desc = new File(savepath,picFileName); //FileUtils.copyFile(pic, desc); 《--采用此种方法以下均可省略,较简单 InputStream is = new FileInputStream(pic); OutputStream os = new FileOutputStream(desc); byte[] buf = new byte[1024]; int len; while((len=is.read(buf))!=-1){ os.write(buf); } is.close(); os.close(); } catch (Exception e) { e.printStackTrace(); } 易错点:若写成--》is.read(buf)<0 将无法读取过来, 但是会在目标路径生成一个零字节文件!