java.io.FileNotFoundException(拒绝访问)错误?但文件正在存储

时间:2017-01-31 06:45:17

标签: java tomcat servlets

我收到错误HTTP状态500 - java.io.FileNotFoundException: C:\ sam \ IMAGES(访问被拒绝)同时在文件中保存图像' IMAGES'。我尝试了所有的事情,比如更改文件的权限并尝试将其保存在不同的文件夹中。奇怪的是事情是我的图像实际上存储在我上面提到的文件中。但为什么它仍然显示错误?如何解决此错误?Tomcat属于用户所有权。

My Code:
MySampleUpload.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="FileUploadServlet" method="post"enctype="multipart/form-data">
    <div class="btn btn-success btn-file">
    <i class="fa fa-cloud-upload"></i>
             Browse
    <input type="file" name="file" />
    </div>
    <button type="submit" value="submit" name='submit'>submit</button>`
    </form>
</body>
</html>

FileUploadServlet.java



import java.io.File;
import java.io.IOException;

import javax.imageio.stream.FileImageOutputStream;
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.RandomAccessFile;

/**
 * Servlet implementation class FileUploadServlet
 */
@WebServlet("/FileUploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*10,    // 10 MB 
maxFileSize=1024*1024*50,       // 50 MB
maxRequestSize=1024*1024*100)       // 100 MB
public class FileUploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    private static final String UPLOAD_DIR="IMAGES";
    public FileUploadServlet() {
        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
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //gets absolute path of the web application
        //String applicationPath=request.getServletContext().getRealPath("");
        //construct path of the directory to save the uploaded file
        String UploadFilePath="C:/sam"+File.separator+UPLOAD_DIR;
        //creates the file directory if it doesn't exist
        File FileSaveDir=new File(UploadFilePath);

    if(!FileSaveDir.exists())
        {
            FileSaveDir.mkdirs();
        }

        System.out.println("Upload file Diiirectory"+FileSaveDir.getAbsolutePath());
        String fileName=null;
        //get all parts from request and write it to the file on the server
        for(Part part:request.getParts())
        {
            fileName=getFileName(part);

            part.write(UploadFilePath + File.separator + fileName);

        }
        System.out.println("File Uploaded successfully");
        request.setAttribute("message",fileName+"file uploaded successfully");

        getServletContext().getRequestDispatcher("/response.jsp").forward(request, response);
    }
    private String getFileName(Part part)
    {
    String ContentDisp=part.getHeader("Content-Disposition");
    System.out.println("content-disposition-header"+ContentDisp);
    String[] tokens = ContentDisp.split(";");
    for (String token : tokens) {
        if (token.trim().startsWith("filename")) {
            return token.substring(token.indexOf("=") + 2, token.length()-1);

        }
    } return "";
    }}

2 个答案:

答案 0 :(得分:1)

你的part对象迭代2次,从第一次获取文件名,第二次是null。所以检查部分内的文件名为null。 替换此部分。

for (Part part : request.getParts()) {
            fileName = getFileName(part);
            if (fileName != null && !"".equals(fileName)) {
                part.write(UploadFilePath + File.separator + fileName);
            }

        }

答案 1 :(得分:0)

您也可以使用下面的代码,其中表单组件和文件组件是分开的。

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    try {
        List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
        for (FileItem item : items) {
            if (item.isFormField()) {
                // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                String fieldname = item.getFieldName();
                String fieldvalue = item.getString();
                // ... (do your job here)
            } else {
                // Process form file field (input type="file").
                String fieldname = item.getFieldName();
                String filename = FilenameUtils.getName(item.getName());
                InputStream filecontent = item.getInputStream();
                // ... (do your job here)
            }
        }
    } catch (FileUploadException e) {
        throw new ServletException("Cannot parse multipart request.", e);
    }

    // ...
}