java中使用文件上传时需要使用特定的类库,这里使用commons-files类库进行文件上传,在http://commons.apache.org/proper/commons-fileupload/上下载commons-io和commons-files类库

        DiskFileUpload upload = new DiskFileUpload();
upload.setHeaderEncoding("UTF-8");
List<FileItem> list;
try {
list = upload.parseRequest(request);
// 遍历上传的文件
for(FileItem item:list){
// 判断文件类型
if(item.isFormField()){
String name = item.getName();
String value = item.getString("UTF-8");
}
else{
// 获取上传文件
File remoteFile = new File(new String(item.getName().getBytes(),"UTF-8"));
// 创建保存文件
File file1 = new File(request.getContextPath()+"/attachment",remoteFile.getName());
file1.getParentFile().mkdirs();
file1.createNewFile(); // 创建流进行操作
InputStream inputStream = item.getInputStream();
OutputStream outputStream = new FileOutputStream(file1);
try {
int len = ;
byte[] bt = new byte[];
while( (len = inputStream.read(bt)) > -){
outputStream.write(bt,,len);
} } finally {
// 关闭流
inputStream.close();
outputStream.close();
}
05-13 07:12