• JAVA基础篇—文件上传下载


    /index.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="/web-ajax/js/jquery.min.js"></script>
    </head>
    <body>
      <form action="${pageContext.request.contextPath}/FileServlet" enctype="multipart/form-data" method="post">
       用户: <input type="text" name="username"/><br>
          <input type="file" name="photo"/><br>
          <input type="file" name="photo1"/><br>
          <input type="file" name="photo2"/><br>
          <input type="submit" value="起飞"/>
      </form>
    </body>
    </html>
    View Code

    /downlode.jsp

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
      <a href="${pageContext.request.contextPath}/DownServlet">下载吧</a>
    </body>
    </html>
    View Code

    /class FileServlet

    package com.neuedu.servlet;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.List;
    import java.util.UUID;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    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.FileUploadBase.FileSizeLimitExceededException;
    import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    
    
    
    
    
    @WebServlet("/FileServlet")
    public class FileServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
       
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    	}
    
    	
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		//工厂类,用于构建一个解析器实例。
    		DiskFileItemFactory factory=new DiskFileItemFactory();
    		//创建对象,完成上传
    		ServletFileUpload fileupload=new ServletFileUpload(factory);
    		fileupload.setSizeMax(1024*1500);
    		ServletContext servletContext = request.getServletContext();
    		String realPath = servletContext.getRealPath("/upload");
    		File file=new File(realPath);
    		if (!file.exists()) {
    			file.mkdir();
    		}
    		try {
    			List<FileItem>filelist=fileupload.parseRequest(request);
    			for (FileItem fileItem : filelist) {
    				if (fileItem.isFormField()) {
    					String name = fileItem.getFieldName();
    					String value = fileItem.getString("utf8");
    					System.out.println(name+":"+value);
    				}else {
    					long size = fileItem.getSize();
    					if(size ==0){
    						continue;
    					}
    					String contentType = fileItem.getContentType();
    					String name = fileItem.getName();
    					if(name.contains("\")){
    						name = name.substring(name.lastIndexOf("\")+1);
    					}
    					//uuid_name.jpg
    					String prefix = UUID.randomUUID().toString();
    					prefix = prefix.replace("-","");
    					String fileName = prefix+"_"+name;
    //					String fieldName = fileItem.getFieldName();
    					System.out.println(size+":"+contentType+":--------"+name+":"+fileName);
    					fileItem.write(new File(realPath+"\"+fileName));
    				}
    			}
    		}catch(FileSizeLimitExceededException e){
    			System.out.println("文件大小不可以超过500K");
    		}catch(SizeLimitExceededException e){
    			System.out.println("总大小不可以超过1500k");
    		}  catch (Exception e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
    	}
    
    }
    

      /class DownServlet

    package com.neuedu.servlet;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.PrintWriter;
    
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.io.IOUtils;
    
    
    @WebServlet("/DownServlet")
    public class DownServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
        
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		ServletContext servletContext = request.getServletContext();
    		String fileName="风吹麦浪.mp3";
    		String path = servletContext.getRealPath("/风吹麦浪.mp3");
    		File file=new File(path);
    		String type = servletContext.getMimeType(path);
    		InputStream in=new FileInputStream(file);
    		response.setContentType(type);
    		fileName = new String(fileName.getBytes("gbk"),"iso8859-1");
    		response.setHeader("Content-Disposition", "attachment; filename="+fileName);
    		ServletOutputStream out=response.getOutputStream();
    		IOUtils.copy(in, out);
    		in.close();
    	}
    
    	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		
    		doGet(request, response);
    	}
    
    }
    

      

  • 相关阅读:
    将本地html文件拖到IE8浏览器无法打开,直接弹出一个下载的对话框
    ImageMagick
    64位win8.1系统 运行 32位程序,文件夹路径是中文遇到问题
    Dreamweaver
    JBOSS Spring Web
    spring web应用
    SQL PKG示例
    SQL分区表示例
    Java RMI 框架(远程方法调用)
    Java NIO 进程间通信
  • 原文地址:https://www.cnblogs.com/lc-java/p/7400396.html
Copyright © 2020-2023  润新知