一:文件上傳使用
注意:需要導入commons-fileupload-1.2.1.jar包和commons-io-2.4.jar包
1.創建upload.jsp包含js代碼可以上傳多個文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Upload</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/scripts/jquery-1.7.1.js"></script>
<script type="text/javascript">
$(function () {
var i=2;
$("#addFile").click(function () {
$(this).parent().parent().before("<tr class='file'> <td>File"+
i+":</td><td><input type='file' name='file"+
i+"'/></td></tr>"+"<tr class='desc'><td>Desc"+
i+":</td> <td><input type='text' name='desc"+
i+"'/><button id='delete"+i+"'>刪除</button></td> </tr>");
i++;
//獲取新添加的刪除按鈕
$("#delete"+(i-1)).click(function () {
var $tr=$(this).parent().parent();
$tr.prev("tr").remove();
$tr.remove();
//對i重新排序
$(".file").each(function (index) {
var n=index+1;
$(this).find("td:first").text("File"+n);
$(this).find("td:last input").attr("name","file"+n);
});
$(".desc").each(function (index) {
var n=index+1;
$(this).find("td:first").text("Desc"+n);
$(this).find("td:last input").attr("name","desc"+n);
});
i=i-1;
});
return false;
});
});
</script>
</head>
<body>
<font color="red"> ${message}</font><br>
<form action="fileUploadServlet" method="post" enctype="multipart/form-data">
<input type="hidden" id="fileNum" name="fileNum" value="1"/>
<table>
<tr><td class="file">File1:</td>
<td><input type="file" name="file1"/><br></td>
</tr>
<tr>
<td class="desc">Desc1:</td>
<td><input type="text" name="desc1"/><br></td>
</tr>
<tr>
<td><input type="submit" id="submit" value="Submit"/></td>
<td><button id="addFile">新增一個附件</button></td>
</tr>
</table>
</form>
</body>
</html>
2.創建FileUploadServlet
public class FileUploadServlet extends HttpServlet {
private static final String FILE_PATH="D:/JavaProject/JavaWebDemo/web/WEB-INF/files";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String path=null;
//獲取properties文件中的屬性值
String fileMaxSize = FileUploadAppProperties.getInstance().getProperty("file.max.size");
String totalFileMaxSize = FileUploadAppProperties.getInstance().getProperty("total.file.max.size");
//得到FileItem的集合Item
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 500);
File tempDirectory = new File("d:\\files\\tempDirectory");
factory.setRepository(tempDirectory);
ServletFileUpload upload = new ServletFileUpload(factory);
//設置文件上傳的限制屬性文件的大小需要限制
upload.setSizeMax(Integer.parseInt(totalFileMaxSize));
upload.setFileSizeMax(Integer.parseInt(fileMaxSize));
try {
Map<String,FileItem> uploadFiles=new HashMap<String,FileItem>();
//解析請求得到File Item集合
List<FileItem> items=upload.parseRequest(request);
//構建fileUploadBean的集合
List<FileUploadBean> beans=buildFileUploadBeans(items,uploadFiles);
//校驗擴展名
validateExtName(beans);
Upload(uploadFiles);
saveBeans(beans);
path="/app/success.jsp";
} catch (Exception e) {
e.printStackTrace();
path="/app/upload.jsp";
request.setAttribute("message",e.getMessage());
}
request.getRequestDispatcher(path).forward(request,response);
}
/**
*@ClassName FileUploadServlet
*@Description 校驗擴展名是否合法
*@Param [beans]
*@Return void
*@Date 2020/3/9 17:48
*@Author Roy
*/
private void validateExtName(List<FileUploadBean> beans) {
String exts = FileUploadAppProperties.getInstance().getProperty("exts");
List<String > extList=Arrays.asList(exts.split(","));
for(FileUploadBean bean:beans){
String fileName=bean.getFileName();
String extName=fileName.substring(fileName.lastIndexOf(".")+1);
if(!extList.contains(extName)){
throw new InvalidExtNameException(fileName+"文件的擴展名不合法");
}
}
}
/**
*@ClassName FileUploadServlet
*@Description 利用傳入的FileItem的集合構建FileUploadBean的集合同時填充uploadFiles
*@Param [items, uploadFiles]
*@Return java.util.List<cn.app.com.FileUploadBean>
*@Date 2020/3/9 17:20
*@Author Roy
*/
private List<FileUploadBean> buildFileUploadBeans(List<FileItem> items, Map<String,FileItem> uploadFiles) {
List<FileUploadBean> beans=new ArrayList<>();
Map<String ,String > descs=new HashMap<>();
for(int i=0;i<items.size();i++){
FileItem item=items.get(i);
if(item.isFormField()){
String filedName=item.getFieldName();
String val=item.getString();
descs.put(filedName,val);
}
}
for(int i=0;i<items.size();i++){
FileItem item=items.get(i);
FileUploadBean bean=null;
if(!item.isFormField()){
String filedName=item.getFieldName();
String descName="desc"+filedName.substring(filedName.length()-1);
String desc=descs.get(descName);
String fileName=item.getName();
String filePath=getFilePath(fileName);
bean=new FileUploadBean(fileName,filePath,desc);
beans.add(bean);
uploadFiles.put(bean.getFilePath(),item);
}
}
return beans;
}
/**
*@ClassName FileUploadServlet
*@Description 根據給定的文件名構建一個隨機的文件名
*@Param [fileName]
*@Return java.lang.String
*@Date 2020/3/9 17:19
*@Author Roy
*/
private String getFilePath(String fileName) {
String extName=fileName.substring(fileName.lastIndexOf("."));
Random random=new Random();
String filePath=FILE_PATH+"\\"
+System.currentTimeMillis()+ random.nextInt(10000)+extName;
return filePath;
}
/**
*@ClassName FileUploadServlet
*@Description 保存的方法
*@Param [beans]
*@Return void
*@Date 2020/3/10 16:16
*@Author Roy
*/
private void saveBeans(List<FileUploadBean> beans) {
}
/**
*@ClassName FileUploadServlet
*@Description 文件上傳前的準備工作得到FilePath和InputStream
*@Param [uploadFiles]
*@Return void
*@Date 2020/3/9 17:25
*@Author Roy
*/
private void Upload(Map<String,FileItem> uploadFiles)throws IOException{
for(Map.Entry<String,FileItem> uploadFile:uploadFiles.entrySet()){
String filePath=uploadFile.getKey();
FileItem item=uploadFile.getValue();
Upload(filePath,item.getInputStream());
}
}
/**
*@ClassName FileUploadServlet
*@Description 文件上傳的IO方法
*@Param [filePath, inputStream]
*@Return void
*@Date 2020/3/9 17:25
*@Author Roy
*/
private void Upload(String filePath, InputStream inputStream) throws IOException {
OutputStream out=new FileOutputStream(filePath);
byte[] buffer=new byte[1024];
int len =0;
while((len=inputStream.read(buffer))!=-1){
out.write(buffer,0,len);
}
inputStream.close();
out.close();
System.out.println(filePath);
}
}
二:文件下載
1.創建download.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>downLoad</title>
</head>
<body>
<a href="downloadServlet">DownLoad .pptx</a>
</body>
</html>
2.創建downloadServlet
public class DownLoadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/x-msdownload");
String fileName="";
response.setHeader("Content-Disposition","attachment;filename="+URLEncoder.encode(fileName,"UTF-8"));
OutputStream outputStream=response.getOutputStream();
String pptFileName="D:\\mysql.pptx";
InputStream in=new FileInputStream(pptFileName);
byte[] buffer=new byte[1024];
int len=0;
while((len=in.read(buffer))!=-1){
outputStream.write(buffer,0,len);
}
in.close();
}
}