文件上传如何设置允许上传格式
文件上传如何设置允许上传格式,在点击浏览时,弹出对话框中只出现符合条件的文件
------解决方案--------------------直接上代码:
@SuppressWarnings({"serial", "unchecked"})
public class UploadServlet extends HttpServlet {
private String uploadpath = null;
private String repository = null;
private long singlefilesize = 0;
@Override
public void init() throws ServletException {
// 获取初始化参数的值
uploadpath = getServletConfig().getInitParameter("uploadpath");
repository = getServletConfig().getInitParameter("repository");
singlefilesize = new Long(getServletConfig().getInitParameter("singlefilesize"));
}
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html; charset=GBK");
// Check that we have a file upload request
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
System.out.println("isMultipart: " + isMultipart);
// Create a factory for disk-based file items
DiskFileItemFactory factory = new DiskFileItemFactory();
// Set factory constraints
factory.setSizeThreshold(1024 * 1024 * 3);
factory.setRepository(new File(repository));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// 设置允许上传文件的大小
upload.setFileSizeMax(singlefilesize);
String path = getServletContext().getRealPath(uploadpath);
File dirFile = new File(path);
if(!dirFile.exists()){
dirFile.mkdir();
}
try {
// Parse the request
List<FileItem> items = upload.parseRequest(request);
System.out.println(items.size());
for(FileItem item : items){
if (item.isFormField()) {
String name = item.getFieldName();
String value = item.getString("GBK");
System.out.println("name: " + name);
System.out.println("value: " + value);
request.setAttribute("name", name);
request.setAttribute("value", value);
} else {
String fieldName = item.getFieldName();
[color=#99CC00]//获取文件名,截取判断下
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
Syste