码迷,mamicode.com
首页 > 编程语言 > 详细

java文件上传

时间:2016-09-12 17:13:06      阅读:199      评论:0      收藏:0      [点我收藏+]

标签:

jsp界面代码:

  <body>
  <form action="servlet/UploadServlet" enctype="multipart/form-data" method="post">
     <table>
      <tr>
       <td>文件上传:</td>
       <td>
        <input type="file" name="file1">
       </td>
      </tr>
      <tr>
       <td>
        <input type="submit" value="提交">
       </td>
      </tr>
     </table>
    </form>
  </body>

后台代码:

 

public void doPost(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException {

 

     response.setContentType("text/html");  

 File file1 = null;  

 DiskFileUpload diskFileUpload = new DiskFileUpload();   

try {    

List<FileItem> list = diskFileUpload.parseRequest(request);    

for(FileItem fileItem : list){     

if(fileItem.isFormField()){

          }

else{            

File remoteFile = new File(new String(fileItem.getName().getBytes(),"UTF-8"));      //服务器项目部署路径_E:\tomcat\tomcat\webapps\fileUploadDemo\attachment      

file1 = new File(this.getServletContext().getRealPath("attachment"),remoteFile.getName());     

 file1.getParentFile().mkdirs();     

 file1.createNewFile();            

InputStream inp = fileItem.getInputStream();           

 OutputStream oup = new FileOutputStream(file1);            

byte[] buffer = new byte[1024];      

int len = 0;      

while((len = inp.read(buffer)) > -1){       

oup.write(buffer);      }      

oup.close();      

inp.close();     

}    

}   

} catch (FileUploadException e) {    

// TODO Auto-generated catch block    

e.printStackTrace();  

 }        

}

 

java文件上传

标签:

原文地址:http://www.cnblogs.com/gm007/p/5865215.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!