前端js上传文件 到后端接收文件

摘要:
以下是前端js代码:Fileupload˂=null){FilefullFile=newFile;FilesavedFile=newFile;fi.write;}}System.out。打印;}Catch{//您可以跳转到错误页面e.printStackTrace();}}publicvoinitit()throwsServletException{FileuploadFile=newFile;if(!

下面是前端js代码:

<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=GB18030">
    <title>File upload</title>
</head>
<body>
<!--  // action="fileupload"对应web.xml中<servlet-mapping>中<url-pattern>的设置. -->
    <form name="myform" action="fileupload" method="post"
       enctype="multipart/form-data">
       File:<br>
       <input type="file" name="myfile"><br>
       <br>
       <input type="submit" name="submit" value="Commit">
    </form>
</body>
</html>

下面是后端的java代码:

package com.zj.sample;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;
 

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.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
 

/**
 * Servlet implementation class Upload
 */
@WebServlet("/Upload")
public class Upload extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private String uploadPath = "D:\temp"; // 上传文件的目录
    private String tempPath = "d:\temp\buffer\"; // 临时文件目录
    File tempPathFile; 
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Upload() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    @SuppressWarnings("unchecked")
    public void doPost(HttpServletRequest request, HttpServletResponse response)
           throws IOException, ServletException {
       try {
           // Create a factory for disk-based file items
           DiskFileItemFactory factory = new DiskFileItemFactory();
 
           // Set factory constraints
           factory.setSizeThreshold(4096); // 设置缓冲区大小,这里是4kb
           factory.setRepository(tempPathFile);// 设置缓冲区目录
 
           // Create a new file upload handler
           ServletFileUpload upload = new ServletFileUpload(factory);
 
           // Set overall request size constraint
           upload.setSizeMax(4194304); // 设置最大文件尺寸,这里是4MB
 
           List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
           Iterator<FileItem> i = items.iterator();
           while (i.hasNext()) {
              FileItem fi = (FileItem) i.next();
              String fileName = fi.getName();
              if (fileName != null) {
                  File fullFile = new File(fi.getName());
                  File savedFile = new File(uploadPath, fullFile.getName());
                  fi.write(savedFile);
              }
           }
           System.out.print("upload succeed");
       } catch (Exception e) {
           // 可以跳转出错页面
           e.printStackTrace();
       }
    }
    public void init() throws ServletException {
        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        File tempPathFile = new File(tempPath);
         if (!tempPathFile.exists()) {
            tempPathFile.mkdirs();
        }
     }
}

web.xml 的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"   version="3.0">
  <display-name>tom2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>Upload</servlet-name>
    <servlet-class>com.zj.sample.Upload</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Upload</servlet-name>
    <url-pattern>/home/fileupload</url-pattern>
  </servlet-mapping>
</web-app>

文件结构:

前端js上传文件 到后端接收文件第1张

免责声明:文章转载自《前端js上传文件 到后端接收文件》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇iOS-reveal 的使用jquery 鼠标滚轮事件 插件 Mousewheel下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

JS代码收藏大全

从其他地方找来的,希望对有需要的人带来方便! 1. oncontextmenu="window.event.returnvalue=false" 将彻底屏蔽鼠标右键<table border oncontextmenu=return(false)><td>no</table> 可用于Table 2. <body o...

Servlet3.0与springmvc那些事

 官方文档:https://docs.spring.io/spring/docs/5.0.2.RELEASE/spring-framework-reference/web.html#mvc-servlet-context-hierarchy 以前开发web工程:servlet、filter、listener都需要在web.xml进行注册,包括springm...

实现DataTables搜索框查询结果高亮显示

DataTables是封装好的HTML表格插件,丰富了HTML表格的样式,提供了即时搜索、分页等多种表格高级功能。用户可以编写很少的代码(甚至只是使用官方的示例代码),做出一个漂亮的表格以展示数据。关于DataTables的更多信息,请查看:http://www.datatables.club/、https://datatables.net/。下图将要展示...

JS- 数组去重方法整理

【indexOf】 简单而且可以加中文,但是兼容性不好,indexOF兼容到ie9 1 function uniq(arr) { 2 var temp = []; 3 for (let i = 0; i < arr.length; i++) { 4 if (temp.indexOf(arr[i]) ==...

js 判断大小端存储

时间一长就容易忘记,先记录一下     ArrayBuffer 类似于缓冲区   //var buffer = new ArrayBuffer( unsigned long length)   //根据指定的byte数目创建一个ArrayBuffer, 缓冲区对应的就是内存中的一部分空间。展示成什么样子,看你如何来读取这些内存。   //var uint3...

js客户端获取IP、MAC地址

<HTML><HEAD><TITLE>WMI Scripting HTML</TITLE><META http-equiv=Content-Type content="text/html; charset=gb2312"><META content="MSHTML 6.00.2800.11...