ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

java上传图片到虚拟路径,简单反射

2022-09-09 17:02:21  阅读:215  来源: 互联网

标签:java String servlet javax 虚拟 catch import 上传 public


1.配置tomcat,还有依赖包


进入配置。



选择一个空文件夹作为虚拟路径,配置好下载所需的jar包,点击这可下载




起名字最好是:commons-beanutils-1.8.0
点击+,导入刚刚的五个jar包

2.编写UploadServlet

点击查看的代码
  import org.apache.commons.fileupload.FileItem;
  import org.apache.commons.fileupload.FileItemFactory;
  import org.apache.commons.fileupload.FileUploadException;
  import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  import org.apache.commons.fileupload.servlet.ServletFileUpload;
  import javax.servlet.annotation.WebServlet;
  import javax.servlet.http.HttpServlet;
  import javax.servlet.http.HttpServletRequest;
  import javax.servlet.http.HttpServletResponse;
  import java.io.File;
  import java.io.IOException;
  import java.util.List;
  import java.util.Random;
  import javax.servlet.ServletException;

  @WebServlet(urlPatterns = "/upload")
  public class UploadServlet extends HttpServlet{
      @Override
      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
          FileItemFactory factory=new DiskFileItemFactory();
          ServletFileUpload upload=new ServletFileUpload(factory);
          List<FileItem> fileItems=null;
          upload.setFileSizeMax(1024*1024*5);
          upload.setSizeMax(1024*1024*1);
          try {
              fileItems=upload.parseRequest(req);
          } catch (FileUploadException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
          for (FileItem fileItem : fileItems) {

              if (fileItem.isFormField()) {
                  String fieldName=fileItem.getFieldName();
                  String value=fileItem.getString("utf-8");
                  System.out.println(fieldName+":"+value);
              } else {

                  String uploadPath="E:\\files";
                  File uploadFile=new File(fileItem.getName());
                  String fileName=uploadFile.getName();
                  if (fileName.lastIndexOf(".")!=-1) {
                      String exist=fileName.substring(fileName.lastIndexOf("."));
                      Random random=new Random();
                      fileName=System.currentTimeMillis()+""+(random.nextInt(9000)+1000)+exist;
                      File destFile=new File(uploadPath,fileName);
                      try {
                          fileItem.write(destFile);
                      } catch (Exception e) {
                          // TODO Auto-generated catch block
                          e.printStackTrace();
                      }
                      System.out.println(uploadPath+"\\"+fileName);
                  }
                  resp.sendRedirect("http://127.0.0.1:8080/files/"+fileName);
              }

          }

      }
  }

3.编写LoginServlet

点击查看的代码
            import java.io.IOException;
            import java.lang.reflect.Field;
            import java.math.BigDecimal;

            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 com.izhicheng.dao.User;
            import net.sf.json.JSONObject;
            @WebServlet(urlPatterns = "/login")
            public class LoginServlet extends HttpServlet{
            	public static <E> E getBean(Class cl,HttpServletRequest req) {
            		E obj =null;
            		try {
            			obj=(E) cl.newInstance();
            		} catch (InstantiationException e) {
            			// TODO Auto-generated catch block
            			e.printStackTrace();
            		} catch (IllegalAccessException e) {
            			// TODO Auto-generated catch block
            			e.printStackTrace();
            		}
            		Field[] fields=cl.getDeclaredFields();
            		for (Field field : fields) {
            			String value=req.getParameter(field.getName());
            			if (value!=null) {
            				field.setAccessible(true);
            				try {
            					if (field.getType().equals(Integer.class)) {
            						field.set(obj, Integer.valueOf(value));
            					}else if (field.getType().equals(String.class)) {
            						field.set(obj, value);
            					}else if (field.getType().equals(BigDecimal.class)) {
            						field.set(obj, new BigDecimal(value));
            					}
            				} catch (NumberFormatException e) {
            					// TODO Auto-generated catch block
            					e.printStackTrace();
            				} catch (IllegalArgumentException e) {
            					// TODO Auto-generated catch block
            					e.printStackTrace();
            				} catch (IllegalAccessException e) {
            					// TODO Auto-generated catch block
            					e.printStackTrace();
            				}

            				
            			}
            		}
            		return obj;
            	}
            	
            	@Override
            	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            		User user=getBean(User.class,req);
            		System.out.println(user);
            		resp.setContentType("application/json;charset=utf-8");
            		resp.getWriter().write(user.toString());
            	}
            	@Override
            	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            		doPost(req, resp);
            	}

            }

4.编写User

点击查看的代码
        import java.math.BigInteger;

        public class User {
            String name;
            Integer id;
            BigInteger coin;

            @Override
            public String toString() {
                return "User{" +
                        "name='" + name + '\'' +
                        ", age=" + id +
                        ", coin=" + coin +
                        '}';
            }

            public User() {
                this.name = "wm";
                this.id = 1;
                this.coin = BigInteger.valueOf(50);
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public Integer getAge() {
                return id;
            }

            public void setAge(Integer age) {
                this.id = age;
            }

            public BigInteger getCoin() {
                return coin;
            }

            public void setCoin(BigInteger coin) {
                this.coin = coin;
            }
        }

5.编写前端代码upload.jsp

点击查看的代码
      <%@ page contentType="text/html;charset=UTF-8" %>
      <html>
      <head>
          <title>Second assignment</title>

      </head>
      <body>
      <form action='http://127.0.0.1:8080/upload' method='POST' enctype='multipart/form-data'>
          <label>
              <input type='text' name='name'/>
          </label>
          <br>
          <input  type='file' name='file' id='file' style='display:none'/>
          <img style='width:200px;height:200px;' id='img' alt="" src=""/>
          <input type='submit' />
      </form>
      <a href="/login">映射</a>

      </body>
      <script>
          document.getElementById("img").onclick=function(){
              document.getElementById("file").click();
          }
          document.getElementById("file").onchange=function(){
              const f = this.files[0];
              const fr = new FileReader();
              fr.readAsDataURL(f);
              fr.onload=function(){
                  document.getElementById('img').src=this.result;
              }
          }
      </script>
      </html>

6效果图

自己修改下路径与虚拟路径,jsp在主页写一个 <a href="upload.jsp">登入</a> 跳过来

标签:java,String,servlet,javax,虚拟,catch,import,上传,public
来源: https://www.cnblogs.com/wengming/p/16673383.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有