博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
文件上传的Serlvet类
阅读量:7216 次
发布时间:2019-06-29

本文共 2117 字,大约阅读时间需要 7 分钟。

hot3.png

public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; private ServletFileUpload upload; private final long MAXSize = 4194304*2L;//4*2MB private String filedir=null;           /**     * @see HttpServlet#HttpServlet()     */    public FileUploadServlet() {        super();        // TODO Auto-generated constructor stub    } /**  * 设置文件上传的初始化信息  * @see Servlet#init(ServletConfig)  */ public void init(ServletConfig config) throws ServletException {  FileItemFactory factory = new DiskFileItemFactory();// Create a factory for disk-based file items  this.upload = new ServletFileUpload(factory);// Create a new file upload handler  this.upload.setSizeMax(this.MAXSize);// Set overall request size constraint 4194304  filedir=config.getServletContext().getRealPath("images");  System.out.println("filedir="+filedir); } /**  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)  */ @SuppressWarnings("unchecked") protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  // TODO Auto-generated method stub  PrintWriter out=response.getWriter();  try {   List
 items = this.upload.parseRequest(request);   if(items!=null && !items.isEmpty()){    for (FileItem fileItem : items) {     String filename=fileItem.getName();     String filepath=filedir+File.separator+filename;     System.out.println("文件保存路径为:"+filepath);     File file=new File(filepath);     InputStream inputSteam=fileItem.getInputStream();     BufferedInputStream fis=new BufferedInputStream(inputSteam);        FileOutputStream fos=new FileOutputStream(file);        int f;        while((f=fis.read())!=-1)        {           fos.write(f);        }        fos.flush();        fos.close();        fis.close();     inputSteam.close();     System.out.println("文件:"+filename+"上传成功!");    }   }   System.out.println("上传文件成功!");   out.write("上传文件成功!");  } catch (FileUploadException e) {   e.printStackTrace();   out.write("上传文件失败:"+e.getMessage());  } }}

转载于:https://my.oschina.net/zhengweishan/blog/493322

你可能感兴趣的文章
java基础 静态 static 问在多态中,子类静态方法覆盖父类静态方法时,父类引用调用的是哪个方法?...
查看>>
FlasCC发布说明
查看>>
如何在macOS Sierra中运行CORE Keygen破解程序
查看>>
终极解决方案:windows10资源管理器假死
查看>>
【java】一维数组循环位移方阵
查看>>
Essential Studio for mobile MVC中创建Razor应用程序平台教程
查看>>
java主函数的含义
查看>>
中国大学MOOC —— 学习笔记(四)
查看>>
访问,ringbtn,
查看>>
致橡树
查看>>
一段测试代码,哦哦哦,
查看>>
uiimagepickercontroller,中文,--》摘
查看>>
第四次作业
查看>>
在python中调用js或者nodejs
查看>>
【年终总结】2年计划还是要有的,万一实现了呢?(转自叶小钗)
查看>>
数字图像处理学习笔记(1.1)---位图的读写、几何变换、傅里叶变换、直方图均衡...
查看>>
javascript数组顺序-----1冒泡的另一种比较好理解的写法
查看>>
数据结构-栈的实现之行编译器核心实现
查看>>
C++ Project 积累(2)
查看>>
(1)用VisualSvn Server,Tortoise Svn,AnkhSvn搭建Svn版本控制
查看>>