21xrx.com
2024-09-17 04:49:54 Tuesday
登录
文章检索 我的文章 写文章
最近在开发一个Java Web项目时
2023-06-10 17:00:26 深夜i     --     --
Java 上传 服务器

最近在开发一个Java Web项目时,遇到了需要上传图片到服务器的需求,这里我来分享一下实现方法。在这个过程中,我用到了三个

首先,在前端页面设计好上传的模块,上传文件的按钮和对应的input标签,然后在Servlet中接收文件,并将文件上传到服务器中。代码如下:


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

  //上传文件目录,项目的WebContent下的upload文件夹

  String upload_directory = request.getSession().getServletContext().getRealPath("/") + "upload/";

  File uploadDir = new File(upload_directory);

  if(!uploadDir.exists()){

    uploadDir.mkdir(); //如果目录不存在,创建该目录

  }

  //获取上传的文件

  Part filePart = request.getPart("fileInput"); //从请求中获取上传的文件

  String fileName = getFileName(filePart);

  OutputStream out = null;

  InputStream filecontent = null;

  try {

    out = new FileOutputStream(new File(upload_directory + fileName));

    filecontent = filePart.getInputStream();

    int read = 0;

    final byte[] bytes = new byte[1024];

    while ((read = filecontent.read(bytes)) != -1) {

      out.write(bytes, 0, read);

    }

    //将上传成功的消息返回

    response.getWriter().println("文件上传成功!");

  } catch (FileNotFoundException e) {

    response.getWriter().println("上传失败,文件未找到!");

  } finally {

    if (out != null) {

      out.close();

    }

    if (filecontent != null) {

      filecontent.close();

    }

  }

}

private String getFileName(final Part part) { //获取上传的文件名

  final String partHeader = part.getHeader("content-disposition");

  for (String content : part.getHeader("content-disposition").split(";")) {

    if (content.trim().startsWith("filename")) {

      return content.substring(content.indexOf('=') + 1).trim()

          .replace("\"", "");

    }

  }

  return null;

}

代码中使用了getPart方法获取上传的文件,使用part.getHeader("content-disposition")获取上传文件的信息,通过实现getFileName方法,获取上传的文件名。最终将文件写入服务器的指定目录中。

在前端方面,HTML代码如下:


  

  

这样就可以在Java中实现上传图片到服务器的功能了。希望这篇文章对你有所帮助。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复