文件上传:使用part.write抛出的异常 IOException:Unexpected output data (外层)和 sun.nio.fs.WindowsException:系统找不到指定的路径(内层)

原因是我要测试文件上传到h20230214_2_war_exploded工程目录的upload目录下,一开始没有创建upload这个目录,我以为它会自己创建,因为之前使用输出流都是会自己创建没有的目录的。

报错代码

jsp

<%--
  Created by IntelliJ IDEA.
  User: 19762
  Date: 2023/2/14
  Time: 18:02
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="uploadTest" method="post" enctype="multipart/form-data">
    <input type="text" name="username" value="中国">
    <br>
    <input type="text" name="password" value="中国人">
    <br>
    <input type="file" name="uploadFile">
    <br>
    <input type="file" name="uploadFile">
    <br>
    <input type="file" name="uploadFile">
    <br>
    <input type="submit" value="submit">
</form>
</body>
</html>

servlet

package com.lijianhua;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;


@WebServlet(name = "UploadTest", value = "/uploadTest")
@MultipartConfig
public class UploadTest extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + " " + password);
        //取得上传的目标路径
        String uploadPath = this.getServletContext().getRealPath("/upload");
        System.out.println(uploadPath);
        //处理日期
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
        Collection<Part> parts =
                request.getParts();
        for (Part part : parts) {
            InputStream fileContent = part.getInputStream();
            if (part.getSubmittedFileName() != null) {
                String uploadFileName = sdf.format(new Date());
                uploadFileName += "_" + System.currentTimeMillis() + "_"
                        + Math.random() + "_" + part.getSubmittedFileName();
                uploadFileName = uploadPath + "\\" + uploadFileName;
                part.write(uploadFileName); //报错位置
            }
            fileContent.close();
        }
    }
}

结果报错了

上网查不到结果,我就开始debug到深层

结果只是系统找不到指定的路径,我猜是没有创建upload文件夹,创建后就解决了

posted @ 2023-02-14 22:19  午夜·bicycle  阅读(527)  评论(0编辑  收藏  举报