JAVAEE-文件上传
需要引入的jar文件:commons-fileupload-1.3.2,commons-io-2.5.jar。
下载地址
http://commons.apache.org/proper/commons-fileupload/
http://commons.apache.org/proper/commons-io/
- 通过Servlet实现
package com.upload.servlet;
import java.io.File;
import java.io.IOException;
import java.util.List;
...导入需要的包
public class UploadServlet extends HttpServlet {
private TouXiangService service=new TouXiangServiceImpl();
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
TouXiang tx = new TouXiang();
try {
// 文件上传
// 可以判断当前请求是不是二进制,如果不是可以终止代码
if (!ServletFileUpload.isMultipartContent(request)) {
return;
}
// 获得FileItemFactory类
// 能够创建文件输入流的工厂对象
FileItemFactory factory = new DiskFileItemFactory();
// 获得ServletFileUpload对象
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置最大上传大小
upload.setSizeMax(3 * 1024 * 1024);
// 设置上传字符集(好像不好用)
// upload.setHeaderEncoding("utf-8");
// 通过upload对象中的parseRequest方法获得FileItem类型的集合
List<FileItem> list = upload.parseRequest(request);
// 遍历所有表单元素
for (FileItem fi : list) {
// 迭代到当前表单元素如果是普通元素
if (fi.isFormField()) {
if (fi.getFieldName().equals("username"))
tx.setUsername(fi.getString("utf-8"));
if (fi.getFieldName().equals("gender"))
tx.setGender(fi.getString("utf-8"));
} else {
// 如果是文件域
// 获得用户上传的文件名
// String filename = fi.getName();
// 使用时间偏移量和随机数来生成文件名,减少重复几率
String sui = (int) (Math.random() * 10000000) + "";
String shi = System.currentTimeMillis() + "";
//时间+随机数+上传文件名的后缀名
String filename = shi
+ sui
+ fi.getName().substring(
fi.getName().lastIndexOf("."));
// System.out.println(filename);
// 获得项目在服务器计算机中的真实路径
String path = this.getServletContext()
.getRealPath("upload");
fi.write(new File(path + "/" + filename));
//设置tx对象中的imgname属性为filename
tx.setImgname(filename);
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//写入数据库
int num=service.addTouXing(tx);
//重定向到显示页面
response.sendRedirect("ShowServlet");
}
}
- 通过springmvc 实现
package com.mvc.controller;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
@Controller
@RequestMapping("uploads.do")
public class UploadsController {
@RequestMapping
public String upload(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//获取表单里myfile的数据
List<MultipartFile> list = req.getFiles("myfile");
// 获得真是路径
String path = request.getSession().getServletContext()
.getRealPath("upload");
for (MultipartFile mf : list) {
if (mf.isEmpty())
continue;
// 获得输入流
InputStream inputStream = mf.getInputStream();
// 获得定义文件名,获得后缀名
String fname = System.currentTimeMillis()
+ ""
+ (int) (Math.random() * 1000000)
+ mf.getOriginalFilename().substring(
mf.getOriginalFilename().lastIndexOf("."));
// 获得输出流
OutputStream outputStream = new FileOutputStream(path + "\\"
+ fname);
int len = 0;
// 缓冲
byte[] b = new byte[1024];
// 循环读写
while ((len = inputStream.read(b)) > 0) {
outputStream.write(b, 0, len);
}
inputStream.close();
outputStream.close();
}
return "redirect:main.jsp";
}
}
上传多个
@Controller
@RequestMapping("uploads.do")
public class UploadsController {
@RequestMapping
public String upload(HttpServletRequest request) throws IOException {
MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
//获取表单里myfile的数据
List<MultipartFile> list = req.getFiles("myfile");
// 获得真是路径
String path = request.getSession().getServletContext()
.getRealPath("upload");
for (MultipartFile mf : list) {
if (mf.isEmpty())
continue;
// 获得输入流
InputStream inputStream = mf.getInputStream();
// 获得定义文件名,获得后缀名
String fname = System.currentTimeMillis()
+ ""
+ (int) (Math.random() * 1000000)
+ mf.getOriginalFilename().substring(
mf.getOriginalFilename().lastIndexOf("."));
// 获得输出流
OutputStream outputStream = new FileOutputStream(path + "\\"
+ fname);
int len = 0;
// 缓冲
byte[] b = new byte[1024];
// 循环读写
while ((len = inputStream.read(b)) > 0) {
outputStream.write(b, 0, len);
}
inputStream.close();
outputStream.close();
}
return "redirect:main.jsp";
}
}