当前位置:   article > 正文

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

java 中 限制文件格式

0a0376d6fbbfca7b789097f99fcabe6c.png

85ab6e7298eaf228d5bd957671e04ee8.png

3cef2d75062b82665cd1a632dca4a646.png

cf2b588d005541dc59667a5d012b0b93.png

附件上传:

8e391fe832b23b37ccc840f1a83ccdff.png

4134cee054bbcc9f426468ddc883135d.png

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 {

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

Listlist = 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();

}

}

}f33bfce2efd73d863ffcf29960ecaad3.png

8d8b030b3bebaf9b635f4d8b59255f5d.png

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

String path = request.getContextPath();

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

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

%>

"keyword1,keyword2,keyword3">

* {

font-size: 23px;

}

附件上传

4de7c26df2c9220aafeb7eb3552cc43e.png

a11215fee339b73a1612e78c83ecb44d.png

ccb578d165d7f9bc92f1264d43a91db4.png

5617eb20beddd79d7d04537259193187.png

dc0cf6a381a4d6e21a01fad6cb7885b2.png

30c3b6f79af1f19e57b2e9b83c3ed5c0.png

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

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

方法一:7ddb5d53db1642f58c3801bcbbe382de.png

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

String path = request.getContextPath();

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

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

%>

"keyword1,keyword2,keyword3">

* {

font-size: 23px;

}

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

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;

}

}

附件上传

d64c261da3f22d446429b2addd5d6886.png

8be01fddfb83c1982bed6b853ff28c43.png

方法二:

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

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 {

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

Listlist = 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();

}

}

}

ad99d592213a0544a3715ccc7687bfb7.png

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

0690147b24693d79faab464f50679690.png

be621db3c43b4c102bccfe51e6eea366.png

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

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

5fc85019321caf6867a5f81ca7f92895.png

4cbc4a6b26c966d930c932f1fc6c43f6.png

————0c3c65e8c7001ea35edac04828e40b5f.png

dfb4b0364c93e19cf56e9bd53f8b3f05.png

81c5fdd55739ca1cec1275d23f8dbe2b.png

26ea9bacc071e9428e94dc0a6aa2afa2.png

e5895194b1542a0a9b5a25b02c364b87.png

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号