目录
目录
文章目录
  1. 说明
  2. 最简单明了的代码示例

Ajax上传文件

说明

  • contentType,内容类型,用于定义网络文件的类型和网页的编码,决定文件接收方应该以什么形式、什么编码来读取这个文件。
  • 以前利用form表单来上传数据时,默认的contentType是application/x-www-form-urlencoded,意思是数据被编码成键值对,这是标准的编码格式。如果要来上传文件,那么contentType必须为multipart/form-data,意思是数据被编码为一条消息,页面上的每个控件对应消息中的一个部分。
  • 这里使用到的技术,前端为jQuery的Ajax,后端为Java的servlet。

最简单明了的代码示例

  • HTML,使用最简单的一个表单,包含一个text和file类型的控件。

    1
    2
    3
    4
    5
    6
    7
    <!-- 编码必须为 multipart/form-data -->
    <form id="uploadForm" enctype="multipart/form-data">
    <input type="text" name="description" />
    <input id="file" type="file" name="file" />
    <button id="upload" >upload</button>
    </form>
  • JS

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    function test() {
    var form = document.getElementById('uploadForm');
    var formdata = new FormData(form);
    $.ajax({
    url: 'addnewcommodity', // 后端Java接收地址
    type: 'POST', // 必须为POST方式
    cache: false,
    data: formdata,
    processData: false,
    contentType: false,
    success: function (returndata) {
    alert("success");
    },
    error: function (returndata) {
    alert("error");
    }
    });
    }
    $('#upload2').on('click', function(){
    test2();
    })
  • 到这里前端做的事已经完成了,剩下的就是后端的事情了。

  • Servlet,这里新建一个Servlet,注意这两个注解!很重要。然后关注doGet()和doPost()方法,看后端是如何获取到这两个表单的数据的!

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    @WebServlet("/addnewcommodity")
    @MultipartConfig
    public class AddNewCommodity extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    String description = request.getParameter("description");
    Part imgPart = request.getPart("file");
    // 下面的代码是生成一个输出路径,并将这个文件 imgPart 存储到路径中读者可不比理会,只需关注上面的获取数据。
    Date date = new Date(System.currentTimeMillis());
    SimpleDateFormat sd = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    String temp = sd.format(date); // 获取一个时间戳
    String imgPartFileName = imgPart.getSubmittedFileName();//获取上传文件名
    String imgPartFileNamePrefix = imgPartFileName.substring(0, imgPartFileName.indexOf('.')); // 取出文件的前缀名
    String imgPartFileNameSuffer = imgPartFileName.substring(imgPartFileName.lastIndexOf('.')); // 取出文件的后缀名
    String newFileName = imgPartFileNamePrefix + "_" + temp + imgPartFileNameSuffer; // 生成的新文件名
    String savePath = this.getServletContext().getRealPath("/common/img/commoditypicture/"); // 获取当前servlet的存储路径
    System.out.println(savePath);
    String fileSavePath = savePath + newFileName; // 文件保存路径完成
    OutputStream out = null;
    InputStream filecontent = null;
    PrintWriter writer = response.getWriter();
    try {
    out = new FileOutputStream(fileSavePath);
    filecontent = imgPart.getInputStream();
    int read = 0;
    final byte[] bytes = new byte[1024];
    while ((read = filecontent.read(bytes)) != -1) {
    out.write(bytes, 0, read);
    }
    writer.println("New file " + newFileName + " created at " + fileSavePath);
    } catch (Exception e) {
    writer.println("You either did not specify a file to upload or are "
    + "trying to upload a file to a protected or nonexistent "
    + "location.");
    writer.println("<br/> ERROR: " + e.getMessage());
    } finally {
    if (out != null) {
    out.close();
    }
    if (filecontent != null) {
    filecontent.close();
    }
    if (writer != null) {
    writer.close();
    }
    }
    }
    }