java-web之图片上传(文件上传)FileItemFactory使用

1.FileUpload的初识

   fileUpload是apache的commons组件提供的上传组件,它最主要的工作就是帮我们解析request.getInpustream()。可以参考在线API文档:http://tool.oschina.net/apidocs/apidoc?api=commons-fileupload

使用fileUpload组件首先需要引入两个jar包:

commons-fileUpload.jar
commons-io.jar

使用fileUpload固定步骤:

创建工厂类:DiskFileItemFactory factory=new DiskFileItemFactory();
创建解析器:ServletFileUpload upload=new ServletFileUpload(factory);
使用解析器解析request对象:List<FileItem> list=upload.parseRequest(request);


一个FileItem对象对应一个表单项。FileItem类有如下方法:

  String getFieldName():获取表单项的name的属性值。
  String getName():获取文件字段的文件名。如果是普通字段,则返回null
  String getString():获取字段的内容。如果是普通字段,则是它的value值;如果是文件字段,则是文件内容。
  String getContentType():获取上传的文件类型,例如text/plain、image。如果是普通字段,则返回null。
  long getSize():获取字段内容的大小,单位是字节。
  boolean isFormField():判断是否是普通表单字段,若是,返回true,否则返回false。
  InputStream getInputStream():获得文件内容的输入流。如果是普通字段,则返回value值的输入流。

 

例子:

jsp页面:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>

    <%--表单后面写入enctype 是说明表单不仅有文字还有二进制文件--%>
    <form action="/updownload2/servlet/AddServlet" method="post" enctype="multipart/form-data" >
        用户名:<input type="text" name="name"><br>
        年龄:<input type="text" name="age"><br>
        分数:<input type="text" name="score"><br>
        照片<input type="file" name="photo"> <br>
        <input type="submit" value="提交">
    </form>

    ${error}
</body>
</html>

servlet代码:

package com.bjsxt.servlet;

import com.bjsxt.entity.Student;
import com.bjsxt.service.StudentService;
import com.bjsxt.service.impl.StudentServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class AddServlet2 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.创建文件工厂
        FileItemFactory factory=new DiskFileItemFactory();
        //2.创建解析器
        ServletFileUpload upload=new ServletFileUpload(factory);
        //限制文件上传的大小
        //限制所有的文件上传的大小
        upload.setFileSizeMax(1024*5*16);
        //限制单个文件上传的大小
        upload.setSizeMax(1024*16);
        //设置上传的中文格式
        upload.setHeaderEncoding("utf-8");
        //使用解析器
        List<FileItem>fileItems=null;
        try {
            fileItems=upload.parseRequest(request);
        } catch (FileUploadException e) {
            e.printStackTrace();
            //刚才设置的大小在这里运行的时候,如果超过就会抛出异常
            request.setAttribute("error","文件大小不能超过16kb");
            request.getRequestDispatcher("/add.jsp").forward(request,response);
            return ;
        }
        //开始接受表单的所有数据(包括 文字和文件)
        String name=null;
        int age=0;
        double score=0;
        String fileName=null;
        String uuidName=null;
        String contentType=null;
        for(int i=0;i<fileItems.size();i++){
            //在这里区分普通的文本和文件
            FileItem item=fileItems.get(i);
            //如果是表单数据的话进去处理
            if(item.isFormField()){
                String filedName=item.getFieldName();
                if(filedName.equals("name")){
                    name=item.getString("utf-8");
                }
                if(filedName.equals("age")){
                    age=Integer.parseInt(item.getString());
                }
                if(filedName.equals("score")){
                    score=Double.parseDouble(item.getString());
                }
            }else{
                //得到上传文件的类型
                contentType=item.getContentType();
                //如果文件的上传类型是以下两种的时候就不能上传,跳转回原页面
                if(!"image/jpeg".equals(contentType) && !"image/gif".equals(contentType)){
                    request.setAttribute("error","文件类型不正确");
                    request.getRequestDispatcher("/add.jsp").forward(request,response);
                    return;
                }
                //设置文件即将存储的格式
                File dir=new File("d:/upload");
                //当该路径下没有这个文件,就创建一个文件
                if(!dir.exists()){
                    dir.mkdirs();
                }
                //得到文件的名字  包含.jpg啊之类的后缀
                fileName=item.getName();
                //为了防止文件重名导致覆盖的问题,我们引入了UUId
                UUID uuid=UUID.randomUUID();
                //在这里设置了文件吗 UUid名.jpg
                uuidName=uuid.toString()+fileName.substring(fileName.lastIndexOf("."));
                //存储文件
                File file=new File(dir,uuidName);
                try {
                    item.write(file);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }

        request.setCharacterEncoding("utf-8");

        Student stu=new Student(name,age,score,fileName,uuidName,contentType);
        //stuService.save添加图片的方法
        StudentService stuService=new StudentServiceImpl();
        int n= stuService.save(stu);

        //页面跳转
        if(n!=0){
            //重定向:/后面要跟上下文路径  /stumgr   /stumgr2
            response.sendRedirect(request.getContextPath()+"/servlet/ShowAllServlet");
        }else{
            request.setAttribute("mess", "添加失败!");
            request.getRequestDispatcher("/add.jsp").forward(request, response);
        }


    }
}

 

  • 10
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
Java使用HttpURLConnection上传文件可以通过以下步骤实现: 1. 创建URL对象,指定上传文件的URL地址。 2. 打开HTTP连接,并设置请求方法为POST。 3. 设置HTTP请求头部信息,包括Content-Type和boundary。 4. 设置HTTP请求体信息,包括上传文件的内容和分割线。 5. 读取服务器端返回的响应信息。 示例代码如下: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) throws Exception { String urlStr = "http://example.com/upload"; String filePath = "C:/test.txt"; URL url = new URL(urlStr); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("POST"); conn.setDoOutput(true); String boundary = "---------------------------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); OutputStream out = conn.getOutputStream(); // 写入分割线 out.write(("--" + boundary + "\r\n").getBytes()); // 写入文件名 out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + filePath + "\"\r\n").getBytes()); // 写入文件类型 out.write(("Content-Type: application/octet-stream\r\n").getBytes()); // 写入空行 out.write(("\r\n").getBytes()); // 写入文件内容 FileInputStream fileIn = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int len; while ((len = fileIn.read(buffer)) != -1) { out.write(buffer, 0, len); } fileIn.close(); // 写入空行 out.write(("\r\n").getBytes()); // 写入分割线 out.write(("--" + boundary + "--\r\n").getBytes()); out.flush(); out.close(); // 读取响应内容 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` 其中,filePath为需要上传的文件路径,urlStr为服务器端接收文件的URL地址。在示例代码中,我们使用了multipart/form-data类型的请求体格式,可以在请求头部信息中设置Content-Disposition、Content-Type等参数。同时,我们也设置了一个分割线boundary,用于分隔不同的请求体部分。最后,我们通过读取服务器端返回的响应信息,来获取上传文件的结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值