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


1.配置tomcat,还有依赖包

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

进入配置。

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

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

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

起名字最好是: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上传图片到虚拟路径,简单反射

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/288470.html

(0)
上一篇 2022年9月9日
下一篇 2022年9月9日

相关推荐

发表回复

登录后才能评论