Java 如何使用servlet将图像保存在我的项目文件夹中?

Java 如何使用servlet将图像保存在我的项目文件夹中?,java,servlets,file-upload,Java,Servlets,File Upload,} 这可以正常工作,但问题是上载的图像文件保存在“C:\Users\XYZ\Documents\NetBeansProjects\ImageUpload\build\web\images”中,但我的要求是图像必须存储在名为images的项目文件夹中,即(C:\Users\XYZ\Documents\NetBeansProjects\ImageUpload\web\images),你能告诉我在哪里更改代码吗 提前谢谢。好的,我会给你最简单的解决方案 首先创建servlet并将以下行添加到最上面的

}

这可以正常工作,但问题是上载的图像文件保存在“C:\Users\XYZ\Documents\NetBeansProjects\ImageUpload\build\web\images”中,但我的要求是图像必须存储在名为images的项目文件夹中,即(C:\Users\XYZ\Documents\NetBeansProjects\ImageUpload\web\images),你能告诉我在哪里更改代码吗


提前谢谢。

好的,我会给你最简单的解决方案

  • 首先创建servlet并将以下行添加到最上面的servlet clas
  • @WebServlet(name=“FileUploadServlet”,urlPatterns={”/upload“})
  • @多重配置
  • 然后在post方法内部复制并粘贴我在下面发布的post方法内部的内容

  • 然后复制函数getFileName并将其粘贴到doPost()方法下面

tut install/examples/web/fileupload/web/index.HTML中的HTML格式如下:

文件上传
文件:

目的地:
当客户端需要将数据作为请求的一部分发送到服务器时,例如在上载文件或提交完成的表单时,使用POST request方法。相反,GET请求方法只向服务器发送URL和头,而POST请求也包括消息体。这允许将任意长度的任何类型的数据发送到服务器。POST请求中的标题字段通常指示消息正文的Internet媒体类型。 提交表单时,浏览器会将内容以流式方式传输,将所有部分组合在一起,每个部分表示表单的一个字段。零件以输入元素命名,并使用名为boundary的字符串分隔符相互分隔。 这是选择sample.txt作为将上载到本地文件系统上tmp目录的文件后,从fileupload表单提交的数据的样子: POST/fileupload/upload HTTP/1.1 主机:本地主机:8080 内容类型:多部分/表单数据; 边界=------------------------------------263081694432439 内容长度:441 -----------------------------263081694432439 内容配置:表单数据;name=“file”;filename=“sample.txt” 内容类型:文本/纯文本 样本文件中的数据 -----------------------------263081694432439 内容配置:表单数据;name=“目的地” /tmp -----------------------------263081694432439 内容配置:表单数据;name=“上传” 上传 -----------------------------263081694432439-- servlet FileUploadServlet.java可以在tut install/examples/web/fileupload/src/java/fileupload/目录中找到。servlet的开头如下所示: @WebServlet(name=“FileUploadServlet”,urlPatterns={”/upload“}) @多重配置 公共类FileUploadServlet扩展了HttpServlet{ 专用最终静态记录器= getLogger(FileUploadServlet.class.getCanonicalName());
@WebServlet注释使用urlPatterns属性定义servlet映射

@MultipartConfig注释表示servlet希望使用multipart/form数据MIME类型发出请求

processRequest方法从请求中检索目标和文件部分,然后调用getFileName方法从文件部分检索文件名。然后,该方法创建一个FileOutputStream并将文件复制到指定的目标。该方法的错误处理部分捕获并处理一些最常见的REA说明找不到文件的原因。processRequest和getFileName方法如下所示:

<!DOCTYPE html>
<html lang="en">
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="upload" enctype="multipart/form-data" >
            File:
            <input type="file" name="file" id="file" /> <br/>
            Destination:
            <input type="text" value="/tmp" name="destination"/>
            </br>
            <input type="submit" value="Upload" name="upload" id="upload" />
        </form>
    </body>
</html>


A POST request method is used when the client needs to send data to the server as part of the request, such as when uploading a file or submitting a completed form. In contrast, a GET request method sends a URL and headers only to the server, whereas POST requests also include a message body. This allows arbitrary-length data of any type to be sent to the server. A header field in the POST request usually indicates the message body’s Internet media type.

When submitting a form, the browser streams the content in, combining all parts, with each part representing a field of a form. Parts are named after the input elements and are separated from each other with string delimiters named boundary.

This is what submitted data from the fileupload form looks like, after selecting sample.txt as the file that will be uploaded to the tmp directory on the local file system:

POST /fileupload/upload HTTP/1.1
Host: localhost:8080
Content-Type: multipart/form-data; 
boundary=---------------------------263081694432439
Content-Length: 441
-----------------------------263081694432439
Content-Disposition: form-data; name="file"; filename="sample.txt"
Content-Type: text/plain

Data from sample file
-----------------------------263081694432439
Content-Disposition: form-data; name="destination"

/tmp
-----------------------------263081694432439
Content-Disposition: form-data; name="upload"

Upload
-----------------------------263081694432439--
The servlet FileUploadServlet.java can be found in the tut-install/examples/web/fileupload/src/java/fileupload/ directory. The servlet begins as follows:

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER = 
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());
protectedvoidprocessrequest(HttpServletRequest),
HttpServletResponse(响应)
抛出ServletException、IOException{
setContentType(“text/html;charset=UTF-8”);
//创建路径组件以保存文件
最终字符串路径=request.getParameter(“目的地”);
最终部分filePart=request.getPart(“文件”);
最终字符串文件名=getFileName(filePart);
OutputStream out=null;
InputStream filecontent=null;
最终PrintWriter=response.getWriter();
试一试{
out=新文件outputstream(新文件(path+File.separator
+文件名);
filecontent=filePart.getInputStream();
int read=0;
最终字节[]字节=新字节[1024];
而((read=filecontent.read(bytes))!=-1){
输出。写入(字节,0,读取);
}
writer.println(“新文件”+文件名+”,创建于“+路径);
LOGGER.log(Level.INFO,“文件{0}正在上载到{1}”,
新对象[]{fileName,path});
}捕获(FileNotFoundException fne){
println(“您没有指定要上载的文件,或者”
+“正在尝试将文件上载到受保护或不存在的文件”
+"地点";;
writer.println(“
错误:+fne.getMessage()); LOGGER.log(Level.severy,“文件上载期间出现问题。错误:{0}”, 新对象[]{fne.getMessage()}); }最后{ if(out!=null){ out.close(); } if(filecontent!=null){ filecontent.close(); } if(writer!=null){ writer.close(); } } } 私有字符串getFileName(最后一部分){ 最终字符串partHeader=part.getHeader(“内容处置”); log(Level.INFO,“partHeader={0}”,partHeader); 对于(字符串内容:part.getHeader(“内容处置”).split(;”){ if(content.trim().startsWith(“文件名”)){ 返回content.substring( content.indexOf('=')+1.trim().replace(“\”,”); } } 返回null; }
##将文件动态添加到文件夹的代码##

String filePath=“D:\\folder1Name\\folder2Name\\”;
if(request.getPart(“文件”)!=null)
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
    if (isMultiPart) {
        ServletFileUpload upload = new ServletFileUpload();
        try {
            FileItemIterator itr = upload.getItemIterator(request);
            while (itr.hasNext()) {
                FileItemStream item = itr.next();
                if (item.isFormField()) {
                    String fieldname = item.getFieldName();
                    InputStream is = item.openStream();
                    byte[] b = new byte[is.available()];
                    is.read(b);
                    String value = new String(b);
                    response.getWriter().println(fieldname + ":" + value + "</br>");
                } else {
                    String path = getServletContext().getRealPath("/");
                    if (FileUpload.processFile(path, item)) {
                        response.getWriter().println("Upload Success");
                    } else {
                        response.getWriter().println("Upload Failed");
                    }
                }
            }
        } catch (FileUploadException fue) {
            fue.printStackTrace();
        }
    }
}
public class FileUpload {

public static boolean processFile(String path, FileItemStream item) {
    try {
        File f = new File(path + File.separator + "images");
        if(!f.exists()) {
            f.mkdir();
        }
        File savedFile=new File(f.getAbsolutePath()+File.separator+item.getName());
        FileOutputStream fos=new FileOutputStream(savedFile);
        InputStream is=item.openStream();
        int x=0;
        byte[]b=new byte[1024];
        while((x=is.read(b))!=-1){
            fos.write(b,0,x);
        }
        fos.flush();
        fos.close();
        return true;
    }catch(Exception e){
        e.printStackTrace();
    }
    return false;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <title>File Upload</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <form method="POST" action="upload" enctype="multipart/form-data" >
            File:
            <input type="file" name="file" id="file" /> <br/>
            Destination:
            <input type="text" value="/tmp" name="destination"/>
            </br>
            <input type="submit" value="Upload" name="upload" id="upload" />
        </form>
    </body>
</html>


A POST request method is used when the client needs to send data to the server as part of the request, such as when uploading a file or submitting a completed form. In contrast, a GET request method sends a URL and headers only to the server, whereas POST requests also include a message body. This allows arbitrary-length data of any type to be sent to the server. A header field in the POST request usually indicates the message body’s Internet media type.

When submitting a form, the browser streams the content in, combining all parts, with each part representing a field of a form. Parts are named after the input elements and are separated from each other with string delimiters named boundary.

This is what submitted data from the fileupload form looks like, after selecting sample.txt as the file that will be uploaded to the tmp directory on the local file system:

POST /fileupload/upload HTTP/1.1
Host: localhost:8080
Content-Type: multipart/form-data; 
boundary=---------------------------263081694432439
Content-Length: 441
-----------------------------263081694432439
Content-Disposition: form-data; name="file"; filename="sample.txt"
Content-Type: text/plain

Data from sample file
-----------------------------263081694432439
Content-Disposition: form-data; name="destination"

/tmp
-----------------------------263081694432439
Content-Disposition: form-data; name="upload"

Upload
-----------------------------263081694432439--
The servlet FileUploadServlet.java can be found in the tut-install/examples/web/fileupload/src/java/fileupload/ directory. The servlet begins as follows:

@WebServlet(name = "FileUploadServlet", urlPatterns = {"/upload"})
@MultipartConfig
public class FileUploadServlet extends HttpServlet {

    private final static Logger LOGGER = 
            Logger.getLogger(FileUploadServlet.class.getCanonicalName());
protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");

    // Create path components to save the file
    final String path = request.getParameter("destination");
    final Part filePart = request.getPart("file");
    final String fileName = getFileName(filePart);

    OutputStream out = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();

    try {
        out = new FileOutputStream(new File(path + File.separator
                + fileName));
        filecontent = filePart.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 " + fileName + " created at " + path);
        LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
                new Object[]{fileName, path});
    } catch (FileNotFoundException fne) {
        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: " + fne.getMessage());

        LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}", 
                new Object[]{fne.getMessage()});
    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

private String getFileName(final Part part) {
    final String partHeader = part.getHeader("content-disposition");
    LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
    for (String content : part.getHeader("content-disposition").split(";")) {
        if (content.trim().startsWith("filename")) {
            return content.substring(
                    content.indexOf('=') + 1).trim().replace("\"", "");
        }
    }
    return null;
}
 String filePath = "D:\\folder1Name\\folder2Name\\";




if (request.getPart("file") != null) {
            if (request.getPart("file").getSize() != 0) {
                System.out.println(UName + "UName" + "LoopilKeri");
                final Part filePart = request.getPart("file");
                String folderName = filePath + UName + "//file";//path;
                final String fileName = getFileName(filePart);
                //
                 File file = new File(folderName);
                  if (!file.exists()) {
                 file.mkdirs();
                 }

                OutputStream out = null;
                InputStream filecontent = null;
                final PrintWriter writer = response.getWriter();

                try {
                    out = new FileOutputStream(new File(folderName + File.separator
                            + fileName));
                    filecontent = filePart.getInputStream();
                    StringBuilder sb = new StringBuilder();
                    int read = 0;
                    final byte[] bytes = new byte[1024];
                // byte[] byte1 = new byte[1024];
                    //   byte1=IOUtils.toByteArray(filecontent);
                    //  System.out.println(byte1.toString()); 
                    while ((read = filecontent.read(bytes)) != -1) {
                        sb.append(bytes);
                        System.out.println(bytes);
                        System.out.println(bytes + "0here" + read);

                        out.write(bytes, 0, read);

                    }
                    // writer.println("New file " + fileName + " created at " + folderName);
                    System.out.println("###########################################################################");
                    System.out.println(sb.toString());
                    request.setAttribute("f1", folderName);
                    request.setAttribute("f2", fileName);
                    //   request.setAttribute("f", byte1);
                    System.out.println(sb);
                    System.out.println("###########################################################################");
                    ServletContext se = this.getServletContext();
                // RequestDispatcher rd =se.getRequestDispatcher("/NewServlet");
                    // rd.forward(request, response);
                    //      LOGGER.log(Level.INFO, "File{0}being uploaded to {1}", 
                    //              new Object[]{fileName, folderName});
                } catch (FileNotFoundException fne) {
//                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: " + fne.getMessage());

                    LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
                            new Object[]{fne.getMessage()});
                } finally {
                    if (out != null) {
                        out.close();
                    }
                    if (filecontent != null) {
                        filecontent.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                }
            }
        }
@MultipartConfig(fileSizeThreshold=1024*1024*2, 
maxFileSize=1024*1024*10, 
maxRequestSize=1024*1024*50)