欢迎光临散文网 会员登陆 & 注册

Java Web:附件上传,两种文件上传限制格式及大小方法,学习笔记文件操作【诗书画唱】

2020-10-13 21:25 作者:诗书画唱  | 我要投稿


附件上传:


package com.jy.controller;


import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.List;


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 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;


/**

 * Servlet implementation class UploadServlet

 */

@WebServlet("/up")

public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public UploadServlet() {

        super();

        // TODO Auto-generated constructor stub

    }


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

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

// TODO Auto-generated method stub

this.doPost(request, response);

}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

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

// TODO Auto-generated method stub

//乱码处理

request.setCharacterEncoding("utf-8");

//创建附件上传工厂类

DiskFileItemFactory factory = new DiskFileItemFactory();

//创建文件上传对象

ServletFileUpload upload = new ServletFileUpload(factory); 

//处理选中文件中的中文乱码的

upload.setHeaderEncoding("utf-8");

//设置文件的临界值大小是50K

//1024B就是1KB

factory.setSizeThreshold(1024 * 50);

//设置临时文件夹的路径

File file = new File("D:\\java\\JavaWebFuJianShangChuan\\WebContent\\img");

factory.setRepository(file);

//限制上传文件的大小最大是5MB

//1024KB就是1MB

upload.setSizeMax(1024 * 1024 * 20);

// 1024 * 1024 * 20就是 (1*1)MB*20=20MB

try {

//解析表单提交过来的数据

List<FileItem>list = upload.parseRequest(request);

//对list进行循环遍历

for(FileItem fi : list) {

//flag只有当type="file"的时候,才会为false

Boolean flag = fi.isFormField();

if(flag) {//正常的表单元素:文本输入框,密码输入框,单选框,多选框...

//正常表单元素的处理

}else {//就是type="file"的表单元素

//附件上传的处理

//获取你选中的文件在本机上的路径

String FileFullPath = fi.getName();

System.out.println("你选中的文件路径是:" + FileFullPath);

//根据本机上的路径创建文件对象

File f = new File(FileFullPath);

    //获取文件名

String fileName = f.getName();

System.out.println("你选中的文件名是:" + fileName);

//获取文件的大小

long size = fi.getSize();

System.out.println("你选中的文件的大小是:" + size + "字节");

//获取工程所在的服务器的路径

String path = request.getServletContext().getRealPath("");

System.out.println(path);

//设置将选中的文件上传到服务器的项目的img文件夹下

String fPath = path + "\\img\\" + fileName;

System.out.println("选中的附件上传到项目中的文件位置是:" + fPath);

//进行附件的拷贝

//选中的文件流不能通过f获取,只能通过fi获取

InputStream is = fi.getInputStream();

OutputStream os = new FileOutputStream(fPath);

//进行拷贝

byte []buf = new byte[1024];

int len = 0;

while((len = is.read(buf)) != -1) {

os.write(buf,0,len);

}

//关闭文件流

os.close();

is.close();

}

}

} catch (FileUploadException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}

<%@ page language="java" contentType="text/html; 

charset=UTF-8" pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"

    +request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content=

        "keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            * {

                font-size: 23px;

            }           

        </style>

    </head>

    <body>

        <h1>附件上传</h1>

        <!-- 如果表单中要进行附件上传的话,

                          就必须添加enctype="multipart/form-data" -->

        <form action="up" method="post" enctype="multipart/form-data">

            <input type="text" placeholder="用户名"  name="act" />

            <br>

            <input type="password" placeholder="密码" name="pwd" />

              <br>

            <input type="radio" name="sex" value="男" />男

              <br>

            <input type="radio" name="sex" value="女" />女

              <br>

            <input type="file" name="upload" />

            <br>

            <input type="submit" value="提交" />

        </form>

    </body>

</html>





1、实现附件上传功能。尝试对上传文件的类型进行限制,只能传图片(png,jpg)文件。

之前的都一样,就是jsp界面加上JS事件就可以了:

方法一:



<%@ page language="java" contentType="text/html; 

charset=UTF-8" pageEncoding="UTF-8"%>

<%

    String path = request.getContextPath();

    String basePath = request.getScheme()+"://"

    +request.getServerName()+":"+request.getServerPort()+path+"/";

%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>

    <head>

        <base hreff="<%=basePath%>">

        <title></title>

        <meta http-equiv="pragma" content="no-cache">

        <meta http-equiv="cache-control" content="no-cache">

        <meta http-equiv="expires" content="0">

        <meta http-equiv="keywords" content=

        "keyword1,keyword2,keyword3">

        <meta http-equiv="description" content="This is my page">

        <style type="text/css">

            * {

                font-size: 23px;

            }           

        </style>

        

<script type="text/javascript">

    var isIE = /msie/i.test(navigator.userAgent) && !window.opera;

    function fileChange(target,id) {

        var fileSize = 0;

        var filetypes =[".jpg",".png"];

        var filepath = target.value;

        var filemaxsize = 1024*2;//2M

        if(filepath){

            var isnext = false;

            var fileend = filepath.substring(filepath.lastIndexOf("."));

            if(filetypes && filetypes.length>0){

                for(var i =0; i<filetypes.length;i++){

                    if(filetypes[i]==fileend){

                        isnext = true;

                        break;

                    }

                }

            }

            if(!isnext){

                alert("不接受此文件类型!只能传图片(png,jpg)文件");

                target.value ="";

                return false;

            }

        }else{

            return false;

        }

        if (isIE && !target.files) {

            var filePath = target.value;

            var fileSystem = new ActiveXObject("Scripting.FileSystemObject");

            if(!fileSystem.FileExists(filePath)){

                alert("附件不存在,请重新输入!");

                return false;

            }

            var file = fileSystem.GetFile (filePath);

            fileSize = file.Size;

        } else {

            fileSize = target.files[0].size;

        }

 

        var size = fileSize / 1024;

        if(size>filemaxsize){

            alert("附件大小不能大于"+filemaxsize/1024+"M!");

            target.value ="";

            return false;

        }

        if(size<=0){

            alert("附件大小不能为0M!");

            target.value ="";

            return false;

        }

    }

</script>

    </head>

    <body>

        <h1>附件上传</h1>

        <!-- 如果表单中要进行附件上传的话,

                          就必须添加enctype="multipart/form-data" -->

        <form action="up" method="post" enctype="multipart/form-data">

            <input type="text" placeholder="用户名"  name="act" />

            <br>

            <input type="password" placeholder="密码" name="pwd" />

              <br>

            <input type="radio" name="sex" value="男" />男

              <br>

            <input type="radio" name="sex" value="女" />女

              <br>

            <input type="file" name="upload" onchange="fileChange(this);"/>

            <br>

            <input type="submit" value="提交" />

        </form>

    </body>

</html>

方法二:

前面基本一样,jsp界面的js事件去掉,就是下面的变一下:

package com.SSHC.controller;


import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.List;


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 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;


/**

 * Servlet implementation class UploadServlet

 */

@WebServlet("/up")

public class UploadServlet extends HttpServlet {

private static final long serialVersionUID = 1L;

       

    /**

     * @see HttpServlet#HttpServlet()

     */

    public UploadServlet() {

        super();

        // TODO Auto-generated constructor stub

    }


/**

* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)

*/

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

// TODO Auto-generated method stub

this.doPost(request, response);

}


/**

* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)

*/

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

// TODO Auto-generated method stub

//乱码处理

request.setCharacterEncoding("utf-8");

//创建附件上传工厂类

DiskFileItemFactory factory = new DiskFileItemFactory();

//创建文件上传对象

ServletFileUpload upload = new ServletFileUpload(factory); 

//处理选中文件中的中文乱码的

upload.setHeaderEncoding("utf-8");

//设置文件的临界值大小是50K

//1024B就是1KB

factory.setSizeThreshold(1024 * 200);

//设置临时文件夹的路径

File file = new File("d:\\temp");

factory.setRepository(file);

//限制上传文件的大小最大是5MB

//1024KB就是1MB

upload.setSizeMax(1024 * 1024 * 20);


try {

//解析表单提交过来的数据

List<FileItem>list = upload.parseRequest(request);

//对list进行循环遍历

for(FileItem fi : list) {

//flag只有当type="file"的时候,才会为false

Boolean flag = fi.isFormField();

if(flag) {//正常的表单元素:文本输入框,密码输入框,单选框,多选框...

//正常表单元素的处理

}else {//就是type="file"的表单元素

//附件上传的处理

//获取你选中的文件在本机上的路径

String FileFullPath = fi.getName();

System.out.println("你选中的文件路径是:" + FileFullPath);

//根据本机上的路径创建文件对象

File f = new File(FileFullPath);

    //获取文件名

String fileName = f.getName();

System.out.println("你选中的文件名是:" + fileName);

//获取选中文件的后缀名

//获取到文件中最后一个.的索引

int index = fileName.lastIndexOf('.');

//根据.的位置进行截取

String fix = fileName.substring(index + 1);

System.out.println("文件的后缀名是:" + fix);

//如果后缀名是png,jpg或者gif,就进行附件上传

if(fix.equals("png") || fix.equals("jpg") 

|| fix.equals("gif")) {

//获取文件的大小

long size = fi.getSize();

System.out.println("你选中的文件的大小是:" + size + "字节");

//获取工程所在的服务器的路径

String path = request.getServletContext().getRealPath("");

System.out.println(path);

//设置将选中的文件上传到服务器的项目的img文件夹下

String fPath = path + "\\img\\" + fileName;

System.out.println("选中的附件上传到项目中的文件位置是:" + fPath);

//进行附件的拷贝

//选中的文件流不能通过f获取,只能通过fi获取

InputStream is = fi.getInputStream();

OutputStream os = new FileOutputStream(fPath);

//进行拷贝

byte []buf = new byte[1024];

int len = 0;

while((len = is.read(buf)) != -1) {

os.write(buf,0,len);

}

//关闭文件流

os.close();

is.close();

//http://localhost:8888/j1908021/img/4.png

String p = request.getContextPath();

System.out.println("工程名是:" + p);

String basePath = request.getScheme() + "://" + 

    request.getServerName() + ":" + request.getServerPort()

    + p + "/";

//获取上传的图片在服务器上的路径

String imgPath = basePath + "img\\" + fileName;

System.out.println("图片的显示路径是:" + imgPath);

//将图片的路径传递到show.jsp页面去

request.setAttribute("imgPath", imgPath);

//上传成功以后,跳转到一个show.jsp页面

request.getRequestDispatcher("show.jsp")

    .forward(request, response);

} else {

response.setCharacterEncoding("gbk");

response.getWriter().write("选中的文件不是一个图片,无法上传");

}

}

}

} catch (FileUploadException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}


}





2、在两台电脑之间进行附件上传的操作。




3、学会使用cmd命令:ipconfig查看服务器的ip地址,ping检查跟指定的ip地址的电脑是否连接在同一个网内的

ping 192.168.42.133就是检查你的电脑跟这个ip地址的电脑是否连接在一起了。



————


Java Web:附件上传,两种文件上传限制格式及大小方法,学习笔记文件操作【诗书画唱】的评论 (共 条)

分享到微博请遵守国家法律