JavaWeb(实现文件上传)(一)

  • 通过Servlet来实现文件上传的功能

实现用户将文件上传到服务里的功能

文件上传功能解释:

当用户在前端网页点击文件上传后,javaWeb的servlet会获得用户所提交的文件并且将文件存放到服务器里。

先看servlet端

@MultipartConfig

将该标注配置到服务器servlet上面,否则会忽略掉文件的内容。并且报错,错误信息

严重: Servlet.service() for servlet [com.xyf.web6.UploadServlet] in context with path [/webtest] threw exception
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided

  

用户上传提交的内容会存放到临时的文件中,我们使用getpart来获取Part对象,

并通过Part对象获得流。另外注意导入

commons-fileupload-1.2.2.jar

commons-io-2.1.jar

到web-inf的lib目录下

servlet端的代码

package com.xyf.web6;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/upload")
@MultipartConfig


public class UploadServlet extends HttpServlet {
	
  
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    request.setCharacterEncoding("UTF-8");
        Part part = request.getPart("uploadFile");
	    String inputName=part.getName();
	    InputStream input=part.getInputStream();
	    //想要保存的目标文件的目录下
	    String tagDir=getServletContext().getRealPath("/upload");
	    //避免文件名重复使用uuid来避免,产生一个随机的uuid字符
	    String realFileName=UUID.randomUUID().toString();
	    OutputStream output=new FileOutputStream(new File(tagDir,realFileName));
	    int len=0;
	    byte[] buff=new byte[1024*8];
	    
	    while ((len = input.read(buff)) > -1) {
            output.write(buff, 0, len);
        }

	    input.close();
	    output.close();
	    response.setCharacterEncoding("utf-8");
	    response.getWriter().print("upload success!!");
	
	}

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

}

jsp端的代码,比较简单

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>文件上传</title>
    </head>
    <body>
        <form action="/webtest/upload" method="post" enctype="multipart/form-data">
            <input type="file" name="uploadFile" /> <br/><br/>
            <input type="submit" value="上传" />
        </form>
    </body>
</html>

  

客户端表单中必须指定method=post,因为上传的文件可能很大,并且指定enctype=multipart/form-data使用上传文件专门的编码方式

 enctype="multipart/form-data"

另外客户端还需要使用<input type="file" 选择要上传的文件

服务器启动后:

选择当前电脑上的文件点击上传

 在路径G:eclipseeclipseeclipseworksapceeeeeeee.metadata.pluginsorg.eclipse.wst.server.core mp1wtpwebappswebtestupload

可能会出现文件不存在的错误,这个时候需要先去判断 ,如果不存在就创建,添加以下代码在servlet里

 String uploadFullPath=tagDir;
	    //先创建这个文件
	    File file=new File(uploadFullPath);
	    File ParentFile=file.getParentFile();
	    if(!ParentFile.exists())
	    {
	    	ParentFile.mkdirs();//如果文件夹不存在,就创建文件夹
	    	
	    }

  这样我们的上传就算是完成了,当然这样上传是不安全的。有关上传的安全问题下文中会讲。

原文地址:https://www.cnblogs.com/a986771570/p/8083020.html