java servlet上传图片_servlet上传图片

packageservlet;importjava.io.File;importjava.io.IOException;importjava.io.PrintWriter;importjava.util.ArrayList;importjava.util.List;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.commons.fileupload.FileItem;importorg.apache.commons.fileupload.FileUploadException;importorg.apache.commons.fileupload.disk.DiskFileItemFactory;importorg.apache.commons.fileupload.servlet.ServletFileUpload;/*** 文件上传

*@authorAdministrator

**/

public class UploadServlet extendsHttpServlet {

List piclist=new ArrayList(); //放上传的图片名

public voiddestroy() {super.destroy(); //Just puts "destroy" string in log//Put your code here

}public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {

String path=request.getRealPath("/heads");

DiskFileItemFactory factory=newDiskFileItemFactory();

ServletFileUpload sfu=newServletFileUpload(factory);

sfu.setHeaderEncoding("UTF-8"); //处理中文问题

sfu.setSizeMax(1024*1024); //限制文件大小

try{

List fileItems= sfu.parseRequest(request); //解码请求 得到所有表单元素

for(FileItem fi : fileItems) {//有可能是 文件,也可能是普通文字

if (fi.isFormField()) { //这个选项是 文字

System.out.println("表单值为:"+fi.getString());

}else{//是文件

String fn=fi.getName();

System.out.println("文件名是:"+fn); //文件名//fn 是可能是这样的 c:\abc\de\tt\fish.jpg

fi.write(newFile(path,fn));if (fn.endsWith(".jpg")) {

piclist.add(fn);//把图片放入集合

}

}

}

}catch(Exception e) {

e.printStackTrace();

}//去显示上传的文件

request.setAttribute("pics", piclist);

request.getRequestDispatcher("show").forward(request, response);

}public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {//fix 修改过

doGet(request, response);

}/*** Initialization of the servlet.

*

*@throwsServletException if an error occurs*/

public void init() throwsServletException {//Put your code here

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值