需要导入的jar包有:commons-fileupload、commons-io、commons-logging,均可在Apache官网上进行下载。
首先页面的简易代码:
<body>
<form action="testUp" method="post" enctype="multipart/form-data">
<input type="test" value="123"/>
file:<input type="file" name="myFile"/>
<input type="submit" value="上传"/>
</form>
</body>
其中为何要使用enctype="multipart/form-data"
关于HTML表单如何打包数据文件是由enctype这个属性决定的。enctype有以下几种取值:
1、application/x-www-form-urlencoded在发送前编码所有字符(默认)(空格被编码为’+’,特殊字符被编码为ASCII十六进制字符)
2、multipart/form-data 不对字符编码,在使用包含文件上传控件的表单时,必须使用该值。
3、text/plain 空格转换为 “+” 加号,但不对特殊字符编码。
接下来是服务器端的代码
package cn.com.demo;
import java.io.File;
import java.io.IOException;
import java.util.List;
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.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class TestUp extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
boolean bool = ServletFileUpload.isMultipartContent(req);
if (bool) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(req);
if(items != null)
{
for(FileItem item:items)
{
if(!item.isFormField())
{
//item是一个文件
String fileName = item.getName();
System.out.println(fileName);
int index = fileName.lastIndexOf("\\");
String value = fileName.substring(index);
File target = new File("F:/temp/"+value);
item.write(target);
}else{
System.out.println(item.getFieldName());
System.out.println(item.getString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
下载则在将响应类型设置为x-msdownload
即response.setContentType("application/x-msdonload");
然后在头信息中加入
response.setHeader("Content-Disposition","attachment;filename=XXX.XXX");