博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Servlet实现文件上传
阅读量:3532 次
发布时间:2019-05-20

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

Servlet3.0开始新增了Part接口,专门用来处理文件上传。

package javax.servlet.http;import java.io.IOException;import java.io.InputStream;import java.util.Collection;public interface Part {    public InputStream getInputStream() throws IOException;    public String getContentType();//获得内容属性如image/png    public String getName();//获得input name属性值与request.getPart参数值一致    public String getSubmittedFileName();//获得上传文件名    public long getSize();    public void write(String fileName) throws IOException;//将上传内容写入文件    public void delete() throws IOException;    public String getHeader(String name);//根据标头名称返回标头信息    public Collection
getHeaders(String name);//根据标头名称返回标头信息集合 public Collection
getHeaderNames();//返回标头名称集合}

比较重要的几个方法:

/** * Obtain the content type passed by the browser. * * @return The content type passed by the browser or null if *         not defined. */public String getContentType();
获得文件类型信息,如image/jpeg;image/png。

/** * If this part represents an uploaded file, gets the file name submitted * in the upload. Returns {
@code null} if no file name is available or if * this part is not a file upload. * * @return the submitted file name or {
@code null}. * * @since Servlet 3.1 */public String getSubmittedFileName();
获得上传文件名称,如test.jpg

/** * A convenience method to write an uploaded part to disk. The client code * is not concerned with whether or not the part is stored in memory, or on * disk in a temporary location. They just want to write the uploaded part * to a file. * *  This method is not guaranteed to succeed if called more than once for *  the same part. This allows a particular implementation to use, for *  example, file renaming, where possible, rather than copying all of the *  underlying data, thus gaining a significant performance benefit. * * @param fileName  The location into which the uploaded part should be *                  stored. Relative locations are relative to {
@link * javax.servlet.MultipartConfigElement#getLocation()} * * @throws IOException if an I/O occurs while attempting to write the part */public void write(String fileName) throws IOException;
上传文件。

/** * Obtain the size of this part. * * @return The size of the part if bytes */public long getSize();
获得上传文件大小(字节)。

Demo:

upload.html

    
upload
上传图片:
uploadServlet.java
import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.Part;import java.io.IOException;import java.io.PrintWriter;import java.time.LocalDate;import java.time.LocalTime;import java.time.format.DateTimeFormatter;//import javax.servlet.annotation.MultipartConfig;//import javax.servlet.annotation.WebServlet;/** * Created by N3verL4nd on 2017/1/9. *///@MultipartConfig(location = "D:/JAVA/IdeaProjects/JavaProj/out/artifacts/jspRun_war_exploded/upload")//@WebServlet(name = "uploadServlet", urlPatterns = {"/upload.do"})public class uploadServlet extends HttpServlet {    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("UTF-8");        response.setContentType("text/html;charset=UTF-8");        PrintWriter out = response.getWriter();        Part part = request.getPart("photo");        //获得上传文件名称(实际过程中应该重命名自己想要的格式)        String filename = part.getSubmittedFileName();        //类型检查如:只要图片格式文件        if (part.getContentType().startsWith("image")) {            String finalFileName = getPreFileName() + filename.substring(filename.indexOf('.', 0), filename.length());            //写入文件            //part.write(finalFileName);            out.println("

" + finalFileName + " 上传成功

"); } else { out.println("

上传失败

"); } //返回input标签name值(与request.getPart参数一致) //out.println(part.getName()); /*//返回标头名称集合(如content-disposition;content-type) for (String str : part.getHeaderNames()){ out.println(str + "
"); }*/ /*//根据标头名称返回标头详细信息(如form-data; name="photo"; filename="ing.png") for (String str : part.getHeaders("content-disposition")){ out.println(str + "
"); }*/ /* //返回内容类型 out.println(part.getContentType() + "
"); //返回标头信息 out.println(part.getHeader("content-disposition") + "
"); //返回上传文件大小 out.println(part.getSize() + " 字节"); //返回上传文件名 out.println(part.getSubmittedFileName()); */ //out.println(this.getServletContext().getRealPath("upload")); } //随机生成文件名 private String getPreFileName(){ StringBuilder stringBuilder = new StringBuilder(); LocalDate date = LocalDate.now(); //格式化日期字符串 stringBuilder.append(date.format(DateTimeFormatter.BASIC_ISO_DATE)); LocalTime time = LocalTime.now().withNano(0); //格式化时间字符串 stringBuilder.append(time.format(DateTimeFormatter.ofPattern("HHmmss"))); return stringBuilder.toString(); }}
上传服务器文件名如:20170109214600.png
关于MultipartConfig:

@MultipartConfig

该注解主要是为了辅助 Servlet 3.0 中 HttpServletRequest 提供的对上传文件的支持。该注解标注在 Servlet 上面,以表示该 Servlet 希望处理的请求的 MIME 类型是 multipart/form-data。另外,它还提供了若干属性用于简化对上传文件的处理。具体如下:

表 5. @MultipartConfig 的常用属性

属性名 类型 是否可选 描述
fileSizeThreshold int 当数据量大于该值时,内容将被写入文件。
location String 存放生成的文件地址。
maxFileSize long 允许上传的文件最大值。默认值为 -1,表示没有限制。
maxRequestSize long 针对该 multipart/form-data 请求的最大数量,默认值为 -1,表示没有限制。

转载地址:http://hmfhj.baihongyu.com/

你可能感兴趣的文章
设置zookeeper开机自启动流程
查看>>
CentOS安装mysql5.7的教详细流程
查看>>
项目整合微信扫码登录功能
查看>>
分布式文件系统FastDfs的搭建
查看>>
Springboot项目利用Java客户端调用FastDFS
查看>>
全文检索工具elasticsearch的安装和简单介绍
查看>>
利用Kibana学习全文检索工具elasticsearch
查看>>
SpringBoot在Test测试类或自定义类中通过@Autowired注入为null
查看>>
使用docker搭建YAPI服务
查看>>
西南科技大学OJ题 邻接表到邻接矩阵1056
查看>>
西南科技大学OJ题 有向图的出度计算1057
查看>>
西南科技大学OJ题 有向图的最大出度计算1059
查看>>
西南科技大学OJ题 带权有向图计算1063
查看>>
oracle主键自增触发器编写
查看>>
String与StringBuilder与StringBuffer三者的差别
查看>>
各种IO流之间的关系和区别
查看>>
SSM如何实现上传单图片
查看>>
SSM环境下java如何实现语音识别(百度语音识别版)
查看>>
ajax方法参数的用法和他的含义
查看>>
数据库基础技巧及用法
查看>>