Java中的文件上传

来源:互联网 发布:全景天窗 知乎 编辑:程序博客网 时间:2024/06/05 05:15
Java中的文件上传
要实现文件上传,首先要在前端定义一个文件传入的入口。
在我的实例中,我是在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目录下;


原创粉丝点击