• 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();//如果文件夹不存在,就创建文件夹
    	    	
    	    }
    

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

  • 相关阅读:
    微服务迁移记(二):注册中心(consul搭建)
    微服务迁移记(一):技术架构
    小程序入坑记录
    不思量,自难忘:我的10年程序生涯
    your password has expired.to log in you must change it
    Javascript中 a.href 和 a.getAttribute('href') 结果不完全一致
    PHP不使用递归的无限级分类
    百度移动搜索自动转码太坑爹,JS跳转地址会被抓取
    iScroll 下 a 标签失效
    浏览器的云加速可能导致IP统计异常
  • 原文地址:https://www.cnblogs.com/a986771570/p/8083020.html
Copyright © 2020-2023  润新知