使用servletfileupload实现表单文件和数据的一起上传

来源:互联网 发布:js截取字符串返回数组 编辑:程序博客网 时间:2024/06/05 22:56

首先导入两个jar包

DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("GB2312");
List items = null;
int companyID = 0;
int companyState = 0;
int companySort = 0;
String companyName = null;
String companyArea = null;
String companySize = null;
String companyType = null;
String companyBrief = null;
String companyPic = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
CompanyDAO dao = new CompanyDAO();
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) { // 如果是表单域 ,就是非文件上传元素
String name = item.getFieldName(); // 获取name属性的值
String value = item.getString("utf-8"); // 获取value属性的值

//非文件元素分别与表单文本框的名称进行匹配
if (name.equals("companyName")) {
companyName = value;
companyPic = "F:/test/"+companyName+".jpg";
System.out.println("companyName   :  "+ companyName);
}
if (name.equals("companyArea")) {
companyArea = value;
System.out.println("companyArea   :  "+ companyArea);
}
if (name.equals("companySize")) {
companySize = value;
System.out.println("companySize   :  "+ companySize);
}
if (name.equals("companyType")) {
companyType = value;
System.out.println("companyType   :  "+ companyType);
}
if (name.equals("companyBrief")) {
companyBrief = value;
System.out.println("companyBrief   :  "+ companyBrief);
}
if (name.equals("companyID")) {

companyID = Integer.parseInt(value);
System.out.println("ID   :  "+ companyID);

}
if (name.equals("companyState")) {
companyState = Integer.parseInt(value);
System.out.println("companyState   :  "+ companyState);
}
if (name.equals("companySort")) {
companySort = Integer.parseInt(value);
System.out.println("companySort   :  "+ companySort);
}


else {//处理文件
String fieldName = item.getFieldName(); // 文件域中name属性的值
String fileName = item.getName(); // 文件的全路径,绝对路径名加文件名
String contentType = item.getContentType(); // 文件的类型
long size = item.getSize(); // 文件的大小,以字节为单位
File saveFile = new File(companyPic); // 定义一个file指向一个具体的文件
try {
item.write(saveFile);// 把上传的内容写到一个文件中
} catch (Exception e) {
e.printStackTrace();
}
}
}

只需要修改中间部分便可实现表单数据和文件的同步上传

阅读全文
0 0