java上传文件到服务器

只有tomcat,所以就上传到本地的磁盘了,其实就是相当于在本地将文件复制到别的地方去,只不过经过了一个服务器

下面是代码

首先是一个表单

文件上传三要素;
1.文件上传项的type属性值必须是file ===>>>才会有文件上传窗口!
2.表单提交方式必须是post ===>>>get对提交数据大小有限制!
3.表单form的enctype属性值必须是multipart/form-data
默认是application/x-www-form-urlencoded:将整个表单作为一个整休!提交表单的数据都是文本数据(value属性值!) multipart/form-data:它会将整个表单拆分为多个部分!(有普通项和上传项)
普通项:提交的value属性文本值上传项:提交的value属性文本值的同时,还可以添加文件的数据!

<%--
  Created by IntelliJ IDEA.
  User: 16949
  Date: 2022/6/1
  Time: 15:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>文件上传</title>
    </head>
    <body>
        <form action="${pageContext.request.contextPath}/fileuploadServlet" enctype="multipart/form-data" method="post">
            昵称<input type="text" name="nickname"><br/>
            头像<input type="file" name="picture"><br/>
            <input type="submit" value="提交">
        </form>
    </body>
</html>

长这样,有点丑

java上传文件到服务器_第1张图片

fileuploadServlet.java 这个servlet类是

package com.itheima.web.servlet;

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;
import org.apache.commons.io.IOUtils;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * @program:
 * @description
 * @author: YunLong
 **/
@WebServlet(urlPatterns = "/fileuploadServlet")
public class fileuploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // 处理响应中文乱码    
        response.setContentType("text/html;charset=utf-8");
        //创建文件磁盘工厂对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //2.通过磁盘工厂对象获得解析器对象
        ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
        //3.通过解析器对象获得request域中的对象
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            // 将普通项的数据存入map中
            HashMap<String,String> map = new HashMap<>();
            //System.out.println(fileItems.size());//2
            for (FileItem fileItem : fileItems) {
                if(fileItem.isInMemory()){
                    String fieldName = fileItem.getFieldName();//nickname name
                    String string = fileItem.getString();//jack value
                    map.put(fieldName,string);
                }
                else{
                    String name = fileItem.getName();
                    String s = name.substring(name.lastIndexOf("."));//.后缀名
                    String s1 = name.substring(0, name.lastIndexOf("."));//文件名字
                    InputStream is = fileItem.getInputStream();
                    OutputStream os = new FileOutputStream("d:/javazaqizaba/"+s1+s);
                    //数据对拷
                    IOUtils.copy(is,os);
                    //关闭流
                    is.close();
                    os.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // 处理请求的中文乱码    
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

}

java上传文件到服务器_第2张图片

fileuploadServlet.java
package com.itheima.web.servlet;

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;
import org.apache.commons.io.IOUtils;
import sun.nio.ch.IOUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.List;

/**
 * @program:
 * @description
 * @author: YunLong
 **/
@WebServlet(urlPatterns = "/fileuploadServlet")
public class fileuploadServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // 处理响应中文乱码    
        response.setContentType("text/html;charset=utf-8");
        //创建文件磁盘工厂对象
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        //通过磁盘工厂对象获得解析器对象
        ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
        try {
        //通过解析器对象获得request域中的对象
            List<FileItem> fileItems = fileUpload.parseRequest(request);
            // 将普通项的数据存入map中
            HashMap<String,String> map = new HashMap<>();
            //System.out.println(fileItems.size());//2
            for (FileItem fileItem : fileItems) {
                if(fileItem.isInMemory()){
                    String fieldName = fileItem.getFieldName();//nickname name
                    String string = fileItem.getString();//jack value
                    map.put(fieldName,string);
                }
                else{
                    String name = fileItem.getName();
                    String s = name.substring(name.lastIndexOf("."));//.后缀名
                    String s1 = name.substring(0, name.lastIndexOf("."));//文件名字
                    InputStream is = fileItem.getInputStream();
                    OutputStream os = new FileOutputStream("d:/javazaqizaba/"+s1+s);
                    //数据对拷
                    IOUtils.copy(is,os);
                    //关闭流
                    is.close();
                    os.close();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }

    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
            IOException {
        // 处理请求的中文乱码    
        request.setCharacterEncoding("utf-8");
        doGet(request, response);
    }

}

其中,用到了这两个.jar包
在这里插入图片描述
如果有需要请联系我打给你。

你可能感兴趣的:(java学习笔记,服务器,java,运维,java-ee,intellij-idea)