JAVA基础篇—文件上传下载

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JAVA基础篇—文件上传下载相关的知识,希望对你有一定的参考价值。

/index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript" src="/web-ajax/js/jquery.min.js"></script>
</head>
<body>
  <form action="${pageContext.request.contextPath}/FileServlet" enctype="multipart/form-data" method="post">
   用户: <input type="text" name="username"/><br>
      <input type="file" name="photo"/><br>
      <input type="file" name="photo1"/><br>
      <input type="file" name="photo2"/><br>
      <input type="submit" value="起飞"/>
  </form>
</body>
</html>
View Code

/downlode.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <a href="${pageContext.request.contextPath}/DownServlet">下载吧</a>
</body>
</html>
View Code

/class FileServlet

package com.neuedu.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
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.FileUploadBase.FileSizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;






@WebServlet("/FileServlet")
public class FileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
   
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		//工厂类,用于构建一个解析器实例。
		DiskFileItemFactory factory=new DiskFileItemFactory();
		//创建对象,完成上传
		ServletFileUpload fileupload=new ServletFileUpload(factory);
		fileupload.setSizeMax(1024*1500);
		ServletContext servletContext = request.getServletContext();
		String realPath = servletContext.getRealPath("/upload");
		File file=new File(realPath);
		if (!file.exists()) {
			file.mkdir();
		}
		try {
			List<FileItem>filelist=fileupload.parseRequest(request);
			for (FileItem fileItem : filelist) {
				if (fileItem.isFormField()) {
					String name = fileItem.getFieldName();
					String value = fileItem.getString("utf8");
					System.out.println(name+":"+value);
				}else {
					long size = fileItem.getSize();
					if(size ==0){
						continue;
					}
					String contentType = fileItem.getContentType();
					String name = fileItem.getName();
					if(name.contains("\\\\")){
						name = name.substring(name.lastIndexOf("\\\\")+1);
					}
					//uuid_name.jpg
					String prefix = UUID.randomUUID().toString();
					prefix = prefix.replace("-","");
					String fileName = prefix+"_"+name;
//					String fieldName = fileItem.getFieldName();
					System.out.println(size+":"+contentType+":--------"+name+":"+fileName);
					fileItem.write(new File(realPath+"\\\\"+fileName));
				}
			}
		}catch(FileSizeLimitExceededException e){
			System.out.println("文件大小不可以超过500K");
		}catch(SizeLimitExceededException e){
			System.out.println("总大小不可以超过1500k");
		}  catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}

  /class DownServlet

package com.neuedu.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;


@WebServlet("/DownServlet")
public class DownServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext servletContext = request.getServletContext();
		String fileName="风吹麦浪.mp3";
		String path = servletContext.getRealPath("/风吹麦浪.mp3");
		File file=new File(path);
		String type = servletContext.getMimeType(path);
		InputStream in=new FileInputStream(file);
		response.setContentType(type);
		fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
		response.setHeader("Content-Disposition", "attachment; filename="+fileName);
		ServletOutputStream out=response.getOutputStream();
		IOUtils.copy(in, out);
		in.close();
	}

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

}

  

以上是关于JAVA基础篇—文件上传下载的主要内容,如果未能解决你的问题,请参考以下文章

python之基础篇——模块与包

JAVA代码审计 任意文件上传篇

JAVA SE基础篇68.动态编译,脚本引擎

《java为何这么简单》基础篇-下载工具与配置java

java基础篇-----认识java

java基础篇-环境变量的配置