上传pdf文件

发布于 2024-10-18 09:06:59 字数 3668 浏览 1 评论 0原文

我想使用下面给出的代码上传 pdf 文件。它提供浏览功能,但不上传文件。当我单击 sendfile 按钮时,它显示 uploadfile.html 代码页。我怎样才能做到这一点??? 给定代码中的错误在哪里???

文件名-upload.html

<%@ page language="java" %>
<HTml>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>  
<% //  for uploading the file we used Encrypt type of multipart/
form-data and input of file type to browse and submit the file %>
  <BODY> <FORM  ENCTYPE="multipart/form-data" ACTION=
"uploadfile.html" METHOD=POST>
        <br><br><br>
      <center><table border="2" >
                    <tr><center><td colspan="2"><p align=
"center"><B>PROGRAM FOR UPLOADING THE FILE</B><center></td></tr>
                    <tr><td><b>Choose the file To Upload:</b>
</td>
                    <td><INPUT NAME="F1" TYPE="file"></td></tr>
                    <tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
             <table>
     </center>      
     </FORM>
</BODY>
</HTML>

文件名--uploadfile.html

<%@ page import="java.io.*" %>
<%
    //to get the content type information from JSP Request Header
    String contentType = request.getContentType();
    //here we are checking the content type is not equal to Null and
 as well as the passed data from mulitpart/form-data is greater than or
 equal to 0
    if ((contentType != null) && (contentType.indexOf("multipart/
form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.
getInputStream());
        //we are taking the length of Content type data
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        //this loop converting the uploaded file into byte code
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, 
formDataLength);
            totalBytesRead += byteRead;
            }

        String file = new String(dataBytes);
        //for saving the file name
        String saveFile = file.substring(file.indexOf("filename=\
"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\")
 + 1,saveFile.indexOf("\""));
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1,
contentType.length());
        int pos;
        //extracting the index of file 
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation))
.getBytes()).length;

        // creating a new file with the same name and writing the 
content in new file
        FileOutputStream fileOut = new FileOutputStream(saveFile);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();

        %><Br><table border="2"><tr><td><b>You have successfully
 upload the file by the name of:</b>
        <% out.println(saveFile); %></td></tr></table> <%
        }
%>

i want to upload a pdf file by using code given below.It give browsing facility but dont upload file. When i click sendfile button Its display uploadfile.html code page. How can i do that???
where is the error in the given code???

filename-upload.html

<%@ page language="java" %>
<HTml>
<HEAD><TITLE>Display file upload form to the user</TITLE></HEAD>  
<% //  for uploading the file we used Encrypt type of multipart/
form-data and input of file type to browse and submit the file %>
  <BODY> <FORM  ENCTYPE="multipart/form-data" ACTION=
"uploadfile.html" METHOD=POST>
        <br><br><br>
      <center><table border="2" >
                    <tr><center><td colspan="2"><p align=
"center"><B>PROGRAM FOR UPLOADING THE FILE</B><center></td></tr>
                    <tr><td><b>Choose the file To Upload:</b>
</td>
                    <td><INPUT NAME="F1" TYPE="file"></td></tr>
                    <tr><td colspan="2">
<p align="right"><INPUT TYPE="submit" VALUE="Send File" ></p></td></tr>
             <table>
     </center>      
     </FORM>
</BODY>
</HTML>

filename--uploadfile.html

<%@ page import="java.io.*" %>
<%
    //to get the content type information from JSP Request Header
    String contentType = request.getContentType();
    //here we are checking the content type is not equal to Null and
 as well as the passed data from mulitpart/form-data is greater than or
 equal to 0
    if ((contentType != null) && (contentType.indexOf("multipart/
form-data") >= 0)) {
        DataInputStream in = new DataInputStream(request.
getInputStream());
        //we are taking the length of Content type data
        int formDataLength = request.getContentLength();
        byte dataBytes[] = new byte[formDataLength];
        int byteRead = 0;
        int totalBytesRead = 0;
        //this loop converting the uploaded file into byte code
        while (totalBytesRead < formDataLength) {
            byteRead = in.read(dataBytes, totalBytesRead, 
formDataLength);
            totalBytesRead += byteRead;
            }

        String file = new String(dataBytes);
        //for saving the file name
        String saveFile = file.substring(file.indexOf("filename=\
"") + 10);
        saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
        saveFile = saveFile.substring(saveFile.lastIndexOf("\\")
 + 1,saveFile.indexOf("\""));
        int lastIndex = contentType.lastIndexOf("=");
        String boundary = contentType.substring(lastIndex + 1,
contentType.length());
        int pos;
        //extracting the index of file 
        pos = file.indexOf("filename=\"");
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        pos = file.indexOf("\n", pos) + 1;
        int boundaryLocation = file.indexOf(boundary, pos) - 4;
        int startPos = ((file.substring(0, pos)).getBytes()).length;
        int endPos = ((file.substring(0, boundaryLocation))
.getBytes()).length;

        // creating a new file with the same name and writing the 
content in new file
        FileOutputStream fileOut = new FileOutputStream(saveFile);
        fileOut.write(dataBytes, startPos, (endPos - startPos));
        fileOut.flush();
        fileOut.close();

        %><Br><table border="2"><tr><td><b>You have successfully
 upload the file by the name of:</b>
        <% out.println(saveFile); %></td></tr></table> <%
        }
%>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情域 2024-10-25 09:06:59

这显然是 Roseindia 代码片段。首先,这是最差学习资源。不要使用它。它只会教导不好的做法。将该网站添加到您的黑名单中。事实上,任何充斥着广告横幅和过时的低质量代码片段的“教程”网站显然都是由业余爱好者维护的,他们主要关注广告收入而不是认真的教学。此类垃圾“教程”网站的其他示例有 javabeat、tutorialspoint、journaldev、javatpoint 等。这些网站的显着共同点是它们起源于印度。

除了您错误地使用了 .html 文件扩展名而不是 .jsp (即使他们正确地使用 .jsp 扩展名展示了他们的示例) ,代码片段存在几个主要问题:

  • HTML 使用 90 年代风格的大写标签。这是不鼓励的。
  • HTML 使用
    标记,这些标记自 1998 年以来已弃用。
  • 业务逻辑与表示逻辑混合在单个 JSP 文件中。 Java 代码属于 Java 类,而不是 JSP 文件。
  • 解析器依赖于 Content-Length 请求标头,该标头本身并不总是存在。如果缺少此标头,代码就会中断。
  • 解析器正在创建该长度的字节数组。当内容长度大于可用服务器内存时,这可能会使服务器崩溃。
  • 解析器使用服务器平台默认字符编码而不是多部分标头中指定的字符编码基于字节数组创建一个String。这可能会导致结果字节格式错误/损坏。
  • DataInputStream 包装器是不必要的,代码没有利用它的任何好处。
  • 等等..
  • 等等..

这简直太可怕了。


从 JSP 上传文件的正确方法是将表单提交给 @MultipartConfig 注解的 servlet 类,然后使用 request.getPart() 获取文件。您可以在此答案中找到一个片段: How to upload files to server using JSP/ Servlet?

这个答案详细阐述了学习 Java EE 的正确方法:Java EE Web 开发,我从哪里开始以及我需要哪些技能?

This is clearly a Roseindia code snippet. First of all, it is the worst learning resource ever. Don't use it. It only teaches bad practices. Add that site to your blacklist. In fact, any "tutorial" site which is littered with advertisement banners and hopelessly outdated low quality code snippets are clearly maintained by amateurs with primary focus on advertisement income instead of on serious teaching. Other examples of such crap "tutorial" sites are javabeat, tutorialspoint, journaldev, javatpoint, etc. Remarkable common thing which those sites have is that they are originated in India.

Apart from the fact that you incorrectly used .html file extension instead of .jsp (even though they presented their examples correctly with .jsp extensions), there are several major problems with the code snippet:

  • The HTML is using '90s style uppercased tags. This is discouraged.
  • The HTML is using <font> and <center> tags which are deprecated since 1998.
  • The business logic is mingled with the presentation logic in a single JSP file. The Java code belongs in a Java class, not in a JSP file.
  • The parser is relying on Content-Length request header which is not always present per se. If this header is absent, the code breaks.
  • The parser is creating a byte array of that length. This may crash the server when the content length is larger than available server memory.
  • The parser is creating a String based on the byte array using server platform default character encoding instead of the one specified in multi part header. This may malform/corrupt the result bytes.
  • The DataInputStream wrapper is unnecessary, the code is not taking any benefit of it.
  • Etc..
  • Etc..

It's simply terrible.


The right way to upload a file from JSP is to submit the form to a @MultipartConfig annotated servlet class and then use request.getPart() to get the file. You can find a snippet in this answer: How to upload files to server using JSP/Servlet?

The right way to learn Java EE is elaborated in this answer: Java EE web development, where do I start and what skills do I need?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文