Java中的文件上传
来源:互联网 发布:全景天窗 知乎 编辑:程序博客网 时间:2024/06/05 05:15
要实现文件上传,首先要在前端定义一个文件传入的入口。
在我的实例中,我是在jsp中写出input标签。
<body>
<form enctype="multipart/form-data" action="${pageContext.request.contextPath}/servlet/UploadServlet2" method="post">
<input type="text" name="username"/><br>
<input type="file" name="file"/><br>
<input type="submit" value="提交"/>
</form>
</body>
上传文件要将form表单的entype属性从默认值改为enctype="multipart/form-data"。否则上传不了。
然后是服务器段开始执性代码;需要到的包有
服务器端的servlet代码
package com.zhang;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
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;
import org.omg.CORBA.PUBLIC_MEMBER;
public class UploadServlet2 extends HttpServlet {
/**
* Constructor of the object.
*/
public UploadServlet2() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//判断上传的表单类型是不是multipart/form-data
boolean isMultipartForm = ServletFileUpload.isMultipartContent(request);
if(!isMultipartForm){
throw new RuntimeException("你的表单格式不正确");
}
//常规的上传逻辑
//创建“能够创建(上传文件对象)”的工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload fileUpload = new ServletFileUpload(factory);
//设置字符编码
fileUpload.setHeaderEncoding("utf-8");
//设置上传文件的大小
fileUpload.setFileSizeMax(2*1024*1024);
//设置上传总文件的大小
fileUpload.setSizeMax(5*1024*1024);
try {
//把表单提交过来的数据进行解析
//FileItem是表单项
List<FileItem> fileItems = fileUpload.parseRequest(request);
//获取每一项数据
for (FileItem item:fileItems) {
if(item.isFormField()){
//它是一个普通的数据
processFormField(item);
}else {
//他是一个文件项
processFieldUpload(item);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void processFormField(FileItem item){
//得到名字
String name = item.getFieldName();
//得到值
String valueString="";
try {
valueString = item.getString("utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("name="+name+":value="+valueString);
}
private void processFieldUpload(FileItem item){
//在应用目录下保存这个文件
String storeDiString = getServletContext().getRealPath("/upload");
//创建文件的目录对象
File realDirectory = new File(storeDiString);
if(!realDirectory.exists()){
//如果没有此目录.创建目录
realDirectory.mkdirs();
}
InputStream in = null;
FileOutputStream fos = null;
try {
//拿到文件的读取流
in = item.getInputStream();
//得到上传文件的文件名
String fileNameString = item.getName();
//不同的浏览器文件名格式不一致
fileNameString = fileNameString.substring(fileNameString.lastIndexOf(File.separator)+1);
fileNameString = UUID.randomUUID().toString()+"_"+fileNameString;
//文件保存对象
File file = new File(realDirectory,fileNameString);
fos= new FileOutputStream(file);
byte[] arr = new byte[1024];
int len=0;
while((len=in.read(arr))!=-1){
fos.write(arr, 0, len);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
if(in!=null){
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
经过上述操作,文件就被存在了tomcat该工程下的Upload目录下;
- Java中的文件上传
- Java中的文件上传
- java项目中的文件上传
- struts中的文件上传
- Struts2中的文件上传
- struts1中的文件上传
- struts2中的文件上传
- Struts中的文件上传
- servlet中的文件上传
- SpringMVC中的文件上传
- struts2中的上传文件
- Flex 中的上传文件
- 传说中的...文件上传!
- C#中的文件上传
- Android中的文件上传
- Struts2中的文件上传
- SpringMVC中的文件上传
- SpringMVC中的文件上传
- redis 数据结构
- 在mac下配置tp5,出现文件读写权限的问题解决办法
- 返回结果的HTTP状态码
- java如何将html过滤为纯文本
- android集成第三方微信登录
- Java中的文件上传
- 专一、自动化代码生成探讨
- 如何快速搭建一个微服务架构?
- 技术分享的好处
- 指针和数组
- reboot流程分析
- 用户管理(二):使用shell脚本批量删除除root用户以外的其它用户
- Java中的lamda表达式---更加高效简洁的表达方式
- 实训第一章