Java Web:附件上傳,兩種文件上傳限制格式及大小方法,學(xué)習(xí)筆記文件操作【詩(shī)書畫唱】




附件上傳:


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");
//創(chuàng)建附件上傳工廠類
DiskFileItemFactory factory = new DiskFileItemFactory();
//創(chuàng)建文件上傳對(duì)象
ServletFileUpload upload = new ServletFileUpload(factory);?
//處理選中文件中的中文亂碼的
upload.setHeaderEncoding("utf-8");
//設(shè)置文件的臨界值大小是50K
//1024B就是1KB
factory.setSizeThreshold(1024 * 50);
//設(shè)置臨時(shí)文件夾的路徑
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 {
//解析表單提交過(guò)來(lái)的數(shù)據(jù)
List<FileItem>list = upload.parseRequest(request);
//對(duì)list進(jìn)行循環(huán)遍歷
for(FileItem fi : list) {
//flag只有當(dāng)type="file"的時(shí)候,才會(huì)為false
Boolean flag = fi.isFormField();
if(flag) {//正常的表單元素:文本輸入框,密碼輸入框,單選框,多選框...
//正常表單元素的處理
}else {//就是type="file"的表單元素
//附件上傳的處理
//獲取你選中的文件在本機(jī)上的路徑
String FileFullPath = fi.getName();
System.out.println("你選中的文件路徑是:" + FileFullPath);
//根據(jù)本機(jī)上的路徑創(chuàng)建文件對(duì)象
File f = new File(FileFullPath);
? ? //獲取文件名
String fileName = f.getName();
System.out.println("你選中的文件名是:" + fileName);
//獲取文件的大小
long size = fi.getSize();
System.out.println("你選中的文件的大小是:" + size + "字節(jié)");
//獲取工程所在的服務(wù)器的路徑
String path = request.getServletContext().getRealPath("");
System.out.println(path);
//設(shè)置將選中的文件上傳到服務(wù)器的項(xiàng)目的img文件夾下
String fPath = path + "\\img\\" + fileName;
System.out.println("選中的附件上傳到項(xiàng)目中的文件位置是:" + fPath);
//進(jìn)行附件的拷貝
//選中的文件流不能通過(guò)f獲取,只能通過(guò)fi獲取
InputStream is = fi.getInputStream();
OutputStream os = new FileOutputStream(fPath);
//進(jìn)行拷貝
byte []buf = new byte[1024];
int len = 0;
while((len = is.read(buf)) != -1) {
os.write(buf,0,len);
}
//關(guān)閉文件流
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>
? ? ? ? <!-- 如果表單中要進(jìn)行附件上傳的話,
? ? ? ? ? ? ? ? ? ? ? ? ? 就必須添加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、實(shí)現(xiàn)附件上傳功能。嘗試對(duì)上傳文件的類型進(jìn)行限制,只能傳圖片(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("附件不存在,請(qǐng)重新輸入!");
? ? ? ? ? ? ? ? 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>
? ? ? ? <!-- 如果表單中要進(jìn)行附件上傳的話,
? ? ? ? ? ? ? ? ? ? ? ? ? 就必須添加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");
//創(chuàng)建附件上傳工廠類
DiskFileItemFactory factory = new DiskFileItemFactory();
//創(chuàng)建文件上傳對(duì)象
ServletFileUpload upload = new ServletFileUpload(factory);?
//處理選中文件中的中文亂碼的
upload.setHeaderEncoding("utf-8");
//設(shè)置文件的臨界值大小是50K
//1024B就是1KB
factory.setSizeThreshold(1024 * 200);
//設(shè)置臨時(shí)文件夾的路徑
File file = new File("d:\\temp");
factory.setRepository(file);
//限制上傳文件的大小最大是5MB
//1024KB就是1MB
upload.setSizeMax(1024 * 1024 * 20);
try {
//解析表單提交過(guò)來(lái)的數(shù)據(jù)
List<FileItem>list = upload.parseRequest(request);
//對(duì)list進(jìn)行循環(huán)遍歷
for(FileItem fi : list) {
//flag只有當(dāng)type="file"的時(shí)候,才會(huì)為false
Boolean flag = fi.isFormField();
if(flag) {//正常的表單元素:文本輸入框,密碼輸入框,單選框,多選框...
//正常表單元素的處理
}else {//就是type="file"的表單元素
//附件上傳的處理
//獲取你選中的文件在本機(jī)上的路徑
String FileFullPath = fi.getName();
System.out.println("你選中的文件路徑是:" + FileFullPath);
//根據(jù)本機(jī)上的路徑創(chuàng)建文件對(duì)象
File f = new File(FileFullPath);
? ? //獲取文件名
String fileName = f.getName();
System.out.println("你選中的文件名是:" + fileName);
//獲取選中文件的后綴名
//獲取到文件中最后一個(gè).的索引
int index = fileName.lastIndexOf('.');
//根據(jù).的位置進(jìn)行截取
String fix = fileName.substring(index + 1);
System.out.println("文件的后綴名是:" + fix);
//如果后綴名是png,jpg或者gif,就進(jìn)行附件上傳
if(fix.equals("png") || fix.equals("jpg")?
|| fix.equals("gif")) {
//獲取文件的大小
long size = fi.getSize();
System.out.println("你選中的文件的大小是:" + size + "字節(jié)");
//獲取工程所在的服務(wù)器的路徑
String path = request.getServletContext().getRealPath("");
System.out.println(path);
//設(shè)置將選中的文件上傳到服務(wù)器的項(xiàng)目的img文件夾下
String fPath = path + "\\img\\" + fileName;
System.out.println("選中的附件上傳到項(xiàng)目中的文件位置是:" + fPath);
//進(jìn)行附件的拷貝
//選中的文件流不能通過(guò)f獲取,只能通過(guò)fi獲取
InputStream is = fi.getInputStream();
OutputStream os = new FileOutputStream(fPath);
//進(jìn)行拷貝
byte []buf = new byte[1024];
int len = 0;
while((len = is.read(buf)) != -1) {
os.write(buf,0,len);
}
//關(guān)閉文件流
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 + "/";
//獲取上傳的圖片在服務(wù)器上的路徑
String imgPath = basePath + "img\\" + fileName;
System.out.println("圖片的顯示路徑是:" + imgPath);
//將圖片的路徑傳遞到show.jsp頁(yè)面去
request.setAttribute("imgPath", imgPath);
//上傳成功以后,跳轉(zhuǎn)到一個(gè)show.jsp頁(yè)面
request.getRequestDispatcher("show.jsp")
? ? .forward(request, response);
} else {
response.setCharacterEncoding("gbk");
response.getWriter().write("選中的文件不是一個(gè)圖片,無(wú)法上傳");
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

2、在兩臺(tái)電腦之間進(jìn)行附件上傳的操作。


3、學(xué)會(huì)使用cmd命令:ipconfig查看服務(wù)器的ip地址,ping檢查跟指定的ip地址的電腦是否連接在同一個(gè)網(wǎng)內(nèi)的
ping 192.168.42.133就是檢查你的電腦跟這個(gè)ip地址的電腦是否連接在一起了。



————
