为什么文件上传不了

为什么文件上传不了

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="f"  uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="h"  uri="http://java.sun.com/jsp/jstl/fmt"%>

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>新建图书信息</title>
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/add.css">
    </head>
    <body>
        <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/dept/list.do">
                        图书信息管理
                    </a>
                </div>
            </div>
        </nav>
        <div class="container">
            <div class="jumbotron">
                <h1>Hello, XXX!</h1>
                <p>请小心地新增图书信息,要是建了一个错误的就不好了。。。</p>
            </div>
            <div class="page-header">
                <h3><small>新建</small></h3>
            </div>
            <form class="form-horizontal" action="<%=request.getContextPath() %>/BookList" method="post" enctype="multipart/form-data">

                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">图书编号 :</label>
                    <div class="col-sm-8">
                        <input name="bookId" class="form-control" id="bookId">
                    </div>
                </div>
                <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">图书名称 :</label>
                    <div class="col-sm-8">
                        <input name="bookName" class="form-control" id="bookName">
                    </div>
                </div>
                <div class="form-group">
                    <label for="categoryId" class="col-sm-2 control-label">分类 :</label>
                    <select id="categoryId" name="categoryId" class="col-sm-2 form-control" style="width: auto;margin-left: 15px">
                             <f:if test="${!empty cList }">
                       <f:forEach var="itme" varStatus="idx" items="${sessionScope.cList}">
                       <option value="${itme.catId}" selected="selected">${itme.catname}</option>
    
                      </f:forEach>
                     </f:if>
                       <!-- 下拉列表的内容要从分类中进行读取,value值是分类id -->
                    </select>
                </div>

                 <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">价格 :</label>
                    <div class="col-sm-8">
                        <input name="bookPrice" class="form-control" id="bookPrice">
                    </div>
                  </div>
                  
                  <div class="form-group" >
                    <label for="name" class="col-sm-2 control-label">图书封面 :</label>
                    <input type="file" id="bookPic" name="bookPic" enctype="multipart/form-data" style="padding-left: 15px">
                  </div>

                  <div class="form-group">
                    <label for="name" class="col-sm-2 control-label">备注 :</label>
                    <div class="col-sm-8">
                        <input name="remarks" class="form-control" id="remarks">
                    </div>
                  </div>

                <div class="form-group">
                    <div class="col-sm-offset-2 col-sm-10">
                        <button type="submit" id="sub" class="btn btn-primary">保存</button>&nbsp;&nbsp;&nbsp;
                    </div>
                </div>
            </form>
        </div>
        <footer class="text-center" >
            copy@imooc
        </footer>
        <script type="text/javascript" src="js/jquery-3.4.0.js"></script>
        <script type="text/javascript">
        var  reg=/^[A-Za-z0-9]{4,15}$/; 
        var  price_reg=/^[0-9]+(.[0-9]+)?$/;
        var  name_reg=/^[\u4E00-\u9FA5A-Za-z0-9]{2,10}$/;
       
     var cat=$("#categoryId").val();
     var  bookPic=$("#bookPic").val();
     var bookId=$("#bookId").val();
      var bookName=$("#bookName").val();
      var bookPrice=$("#bookPrice").val();
      var remarks=$("#remarks").val();
     

        if(cat==null){
       alert("请先添加图书分类");
        sub();
       
         }
     $("#bookPic").change(function(){
        bookPic=$("#bookPic").val();
           var suff= bookPic.substr(bookPic.lastIndexOf("."));
         
       if(suff!=".jpg"&&suff!=".png"&&suff!=".jpeg"&&suff!=".PNG"){
        alert("不支持此图片格式");
       $("#bookPic").val(null);
        sub()
       }
     })
        $("#bookId").change(function(){
         
          bookId=$("#bookId").val();
         
           
         if(!reg.test(bookId)){
          
          alert("编号由只能任意字母数字组成的4-15个字符");
          $("#bookId").val(null);
          sub()
         }
        })
        $("#bookName").change(function(){
          bookName=$("#bookName").val();
         if(!name_reg.test(bookName)){
          alert("请输入汉字或者字母数字2-10");
          $("#bookName").val(null);
          sub()
         }
        })
        $("#remarks").change(function(){
         
            remarks=$("#remarks").val();
         if(!reg.test(remarks)){
          alert("备注由任意字母数字组成的4-15个字符");
            $("#remarks").val(null);
          sub()
         }
        })
        $("#bookPrice").on("change",function(){
          bookPrice=$("#bookPrice").val();
         
         if(!price_reg.test(bookPrice)){
          alert("最少个位最多万位并且只能是正数或小数");
             $("#bookPrice").val(null);
          sub()
         }else{
          $("#bookPrice").val(keepTwoDecimalFull(bookPrice));
          
          
         }
        })
       
        function sub(){
     

            $("#sub").on("submit",function(){
          return false;
         })
        }

     //四舍五入保留2位小数(不够位数,则用0替补)
     function keepTwoDecimalFull(num) {
      var result = parseFloat(num);
      if (isNaN(result)) {
      alert('传递参数错误,请检查!');
      return false;
      }
      result = Math.round(num * 100) / 100;
      var s_x = result.toString();
      var pos_decimal = s_x.indexOf('.');
      if (pos_decimal < 0) {
      pos_decimal = s_x.length;
      s_x += '.';
      }
      while (s_x.length <= pos_decimal + 2) {
      s_x += '0';
      }
      return s_x;
     }
        </script>
    </body>
</html>

package com.imooc.servlet;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class BookList
 */
@WebServlet("/BookList")
public class BookList extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BookList() {
        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)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  DiskFileItemFactory dFactory=new DiskFileItemFactory();
  ServletFileUpload sUpload=new ServletFileUpload(dFactory);
    try {
  List<FileItem> fList= sUpload.parseRequest(request);
        for (FileItem fileItem : fList) {
    if (fileItem.isFormField()) {
    String name= fileItem.getFieldName();
    String value=fileItem.getString("UTF-8");
    System.out.println(name+"-"+value);
    }else {
     // 文件上传项
     // 获得文件的名称:
     String fileName = fileItem.getName();
     System.out.println(fileName);
     // 获得文件的输入流:
     InputStream is = fileItem.getInputStream();
     // 需要将文件写入到服务器的某个路径即可:
     String path = getServletContext().getRealPath("/upload");
     System.out.println(path);
     // 创建输出流 与 输入流进行对接:
     OutputStream os = new FileOutputStream(path+"\\"+fileName);
     int len = 0;
     byte[] b = new byte[1024];
     while((len = is.read(b))!=-1){
      os.write(b, 0, len);
     }
    is.close();
    os.close();
     
    }

   }   
    } catch (FileUploadException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

1.文件写入不了

正在回答 回答被采纳积分+1

登陆购买课程后可参与讨论,去登陆

2回答
提问者 慕先生4377301 2019-06-05 17:39:33

人呢,我重新写了一次还是false

  • 我用同学的代码会报之前老师贴的这个错误,添加判断是否存在,如果不存在,则创建一个文件夹后,就可以正常写入了,同学是或,false,是指那句判断返回的是false呢?,请同学把老师让你加的这个代码贴一下,老师看一下有呦。另外,同学是写的file.mkdirs();呢还是file.mkdir(); 呢?要用前边这个呦,前边的是创建多层文件夹。祝学习愉快,
    2019-06-05 18:15:39
  • 提问者 慕先生4377301 #2
    if (!file.exists()) { file.mkdirs(); }
    2019-06-05 18:20:29
  • 提问者 慕先生4377301 回复 好帮手慕阿莹 #3
    创建的是一个txt文本
    2019-06-05 18:24:41
好帮手慕阿莹 2019-06-05 16:37:20

同学说上传不了,报错信息是什么呢?是否是一下报错呢?

http://img1.sycdn.imooc.com//climg/5cf77de9000157f210270160.jpg

如果是:1、如果同学用的是eclipse,在webapp下创建一个upload文件夹。

2、如果同学用的是idea,在web文件夹下除了创建一个upload文件夹外,再往该文件夹中放一个任意文件(idea不发布空文件夹)

3、或者同学完善一下代码,在代码中做一下判断,先判断一下有没有该文件夹,如果没有,先创建一个

http://img1.sycdn.imooc.com//climg/5cf77f3000015d7e06700160.jpg

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 提问者 慕先生4377301 #1
    没有报错信息,就是写不不到upload ,
    2019-06-05 16:46:17
  • 提问者 慕先生4377301 #2
    存在,但upload文件就是为空
    2019-06-05 16:51:46
  • 提问者 慕先生4377301 #3
    测试了,文件存在,但测试之后返回false,不存在,
    2019-06-05 16:58:42
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师