Servlet-上传

2020-06-20  本文已影响0人  通灵路耳
1、前端页面upload.html 

<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 <!-- 1、method必须是post
      2、enctype表示提交的是二进制文件
      3、type="file"表示上传
  -->
<form action="login" method="post" enctype="multipart/form-data">
  英雄名称:<input type="text" name="heroName" /> <br>
  上传头像 : <input type="file" name="filepath" /> <br>
  <input type="submit" value="上传">
</form>

2、导入jar包
3、配置web.xml
  <servlet>
        <servlet-name>HelloServlet</servlet-name>
        <servlet-class>com.llhc.HelloServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>
4、找到servlet接受上传文件

package com.llhc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class HelloServlet extends HttpServlet {
      
    public void doPost(HttpServletRequest request, HttpServletResponse response) {
  
        String filename = null;
        try {
            //准备:上传文件对象
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //准备:上传文件Servlet
            ServletFileUpload upload = new ServletFileUpload(factory);
            //准备:设置上传文件的大小限制为1M
            factory.setSizeThreshold(1024 * 1024);
            
            //获取:获取传输来的文件,放入List集合
            List items = null;
            try {
                items = upload.parseRequest(request);
            } catch (FileUploadException e) {
                e.printStackTrace();
            }
            
            //获取:遍历文件
            Iterator iter = items.iterator();
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if (!item.isFormField()) {
  
                    //设置:文件名
                    filename = System.currentTimeMillis() + ".jpg";
                    //设置:通过uploaded自动获取到文件地址
                    String photoFolder =request.getServletContext().getRealPath("uploaded");
                    File f = new File(photoFolder, filename);
                    f.getParentFile().mkdirs();
  
                    //获取文件输入流
                    InputStream is = item.getInputStream();
  
                    //获取文件输出流
                    FileOutputStream fos = new FileOutputStream(f);
                    byte b[] = new byte[1024 * 1024];
                    int length = 0;
                    while (-1 != (length = is.read(b))) {
                        fos.write(b, 0, length);
                    }
                    fos.close();
  
                } else {
                    System.out.println(item.getFieldName());
                    String value = item.getString();
                    value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
                    System.out.println(value);
                }
            }
             
            String html = "<img width='200' height='150' src='uploaded/%s' />";
            response.setContentType("text/html");
            PrintWriter pw= response.getWriter();
            pw.format(html, filename);
             
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
图片.png
上一篇下一篇

猜你喜欢

热点阅读