Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/376.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 文件不存在';i'后不上传;处理';相同形式的文本字段_Java_Html_Servlets_File Upload_Multipartform Data - Fatal编程技术网

Java 文件不存在';i'后不上传;处理';相同形式的文本字段

Java 文件不存在';i'后不上传;处理';相同形式的文本字段,java,html,servlets,file-upload,multipartform-data,Java,Html,Servlets,File Upload,Multipartform Data,下面的servlet处理照片和照片标题的上传。servlet工作正常(将照片上传到请求的目录),直到添加了处理相同来源的文本字段的逻辑。现在它既不上传照片也不向数据库提交标题。表单的enctype为多部分/表单数据 HTML <form method="post" action="UploadHandler" enctype="multipart/form-data"> <table> <tr>

下面的servlet处理照片和照片标题的上传。servlet工作正常(将照片上传到请求的目录),直到添加了处理相同来源的文本字段的逻辑。现在它既不上传照片也不向数据库提交标题。表单的enctype为
多部分/表单数据

HTML

    <form method="post" action="UploadHandler" enctype="multipart/form-data">
        <table>

            <tr>
                <td> <strong> Browse photo to submit </strong> </td>
                <td> <input type="file" name="ImageToUpload" value="Upload Photo"/> </td>
            </tr>

            <tr>
                <td> <strong> Give a Caption to this photo </strong>  </td>
                <td> <input type="text" name="CaptionBox" size="40" /></td>
            </tr>

            <tr>
                <td> <strong> Tags &nbsp;<a href="#"> <i> Browse tags </i> </a> </strong> </td>
                <td> <input type="text" size="20" value="Tags" id="tagfield" style="color: #A0A0A4; font-size:16px;" onfocus="emptyTheDefaultValue()"> </td>
            </tr>
            <tr colspan="2">
                <td> <input type="submit" value="submit photo"/> </td>
            </tr>

        </table>
 </form>

浏览要提交的照片
给这张照片加上标题
标签
处理上传的Servlet

package projectcodes;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.File;
import java.util.List;
import java.util.Iterator;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import NonServletFiles.HandleCaption;
import NonServletFiles.ChangePartToString;

public class UploadHandler extends HttpServlet {
@Override
public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
    response.setContentType("text/plain");
    String path = request.getParameter("ImageToUpload"); 
    // Now handle the caption
    // Note : They have a multipart/form-data request
    // Using the servlet API 3.0
    ChangePartToString cpts = new ChangePartToString(request.getPart("CaptionBox")); // get the CaptionBox part 
    String caption = null;

        try {
            caption = cpts.getValue();
            System.out.println(caption); // <<-------- I get this value fine
        }catch(Exception exc) {
            exc.printStackTrace();
            System.out.println(exc);
        }

    PrintWriter writer = response.getWriter();
    try {
        Boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart) {
            Boolean AttemptToUploadFile = true;
            RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
            request.setAttribute("UploadAttempt", AttemptToUploadFile);
            rd.forward(request, response);
        } else {
            DiskFileItemFactory diskFileItem = new DiskFileItemFactory();
            ServletFileUpload fileUpload = new ServletFileUpload(diskFileItem);
            List list = null;

            try {
                list = fileUpload.parseRequest(request);
            }catch(Exception exc) {
            //                    Boolean AttemptToUploadFile = true;
            //                    RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
            //                    request.setAttribute("UploadAttempt", AttemptToUploadFile);
            //                    rd.forward(request, response);
                exc.printStackTrace();
                System.out.println(exc);
            }

            Iterator iterator = list.iterator();
            while(iterator.hasNext()) {
                String emailOfTheUser = null;
                FileItem fileItem = (FileItem)iterator.next();
                if(!fileItem.isFormField()) {
                    String fieldName = fileItem.getFieldName();
                    String fileName = FilenameUtils.getName(fileItem.getName());
                    HttpSession session = request.getSession();
                    if(!session.isNew()) {
                        emailOfTheUser = (String)session.getAttribute("Email");
                    }
                    File file = new File("/home/non-admin/project uploads/project users/" + emailOfTheUser ,fileName);
                    fileItem.write(file);
                    // now since the file has been uploaded , upload the caption to the photo  
                    System.out.println("THE CAPTION :" + caption);
                    HandleCaption hc = new HandleCaption(caption,emailOfTheUser,fileName);
                    hc.SubmitCaptionToTheDatabase(); // This calls invokes a method that submits a caption to the database
                    RequestDispatcher rd = request.getRequestDispatcher("portfolio_one.jsp");
                    String message = "File Uploaded successfully !";
                    request.setAttribute("SuccessMessage", message);
                    rd.forward(request, response);
                }
            }
        }
    }catch(Exception exc) {
        exc.printStackTrace();
        System.out.println(exc);
    }
}
package项目代码;
导入javax.servlet.*;
导入javax.servlet.http.*;
导入java.io.IOException;
导入java.io.PrintWriter;
导入java.io.File;
导入java.util.List;
导入java.util.Iterator;
导入org.apache.commons.fileupload.*;
导入org.apache.commons.fileupload.disk.DiskFileItemFactory;
导入org.apache.commons.fileupload.servlet.ServletFileUpload;
导入org.apache.commons.io.FilenameUtils;
导入NonServletFiles.HandleCaption;
导入NonServletFiles.ChangePartToString;
公共类UploadHandler扩展了HttpServlet{
@凌驾
public void doPost(HttpServletRequest请求、HttpServletResponse响应)引发IOException、ServletException{
response.setContentType(“文本/普通”);
字符串路径=request.getParameter(“ImageToUpload”);
//现在处理标题
//注意:它们有一个多部分/表单数据请求
//使用ServletAPI3.0
ChangePartToString cpts=newchangeparttoString(request.getPart(“CaptionBox”);//获取CaptionBox部分
字符串标题=null;
试一试{
caption=cpts.getValue();

System.out.println(caption);//您正在将Servlet 3.0内置多部分解析器与Apache Commons FileUpload混合使用。您不应该这样做。一旦一个请求体被一个API解析,它就不能再被另一个API解析。当服务器需要解析它时,客户端不会多次重新发送同一个请求体

删除Apache Commons FileUpload。当已经使用Servlet 3.0内置多部分解析器时,您不需要它。您只需要向Servlet类添加
@MultipartConfig
注释,就可以使多部分解析器在普通表单字段和文件字段中都能正常工作。您也不应该使用
getParameterXxx()
方法。另请参见

以下是重写代码的必要步骤,以便获得这两个值:

@WebServlet("/UploadHandler")
@MultipartConfig
public class UploadHandler extends HttpServlet {

    @Override
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException,ServletException {
        Part imageToUpload = request.getPart("ImageToUpload");
        String imageFilename = getFilename(imageToUpload);
        InputStream imageContent = imageToUpload.getInputStream();
        String captionBox = getValue(request.getPart("CaptionBox"));

        // ...
    }

    private static String getFilename(Part part) {
        for (String cd : part.getHeader("content-disposition").split(";")) {
            if (cd.trim().startsWith("filename")) {
                String filename = cd.substring(cd.indexOf('=') + 1).trim().replace("\"", "");
                return filename.substring(filename.lastIndexOf('/') + 1).substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
            }
        }
        return null;
    }

    private static String getValue(Part part) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(part.getInputStream(), "UTF-8"));
        StringBuilder value = new StringBuilder();
        char[] buffer = new char[1024];
        for (int length = 0; (length = reader.read(buffer)) > 0;) {
            value.append(buffer, 0, length);
        }
        return value.toString();
    }

}

您的日志文件中有任何异常吗?@ilya没有。我在问题中提到过。我只看到了启动信息和我使用System.out.println打印的标题(标题),我想如果(!fileItem.isFormField())的话,
会有问题
。您正在使用org.apache.commons处理多部分/表单数据的文本字段和文件字段。如果我使用name=“CaptionBox”photo uploads fine删除处理文本字段的逻辑,那么处理文本字段(多部分类型)的方法是什么使用apache commons。我想我应该使用apache commons而不是servlet 3.0 API!在原始
if(!fileItem.isFormField())
块的
else
中执行此操作。另请参见,您应该确保没有调用
request.getParameter()
request.getPart()
事先,否则Apache Commons FileUpload将无法解析任何内容。谢谢!它成功了。我感谢您为每个问题所做的努力。