如何在服务器上传文件?

时间:2011-03-10 09:59:33

标签: jsp

我想将pdf从客户端上传到服务器。 我使用以下代码..

    <%@ page import="java.io.*" %>
    <%

String contentType = request.getContentType();

if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))     {
    DataInputStream in = new DataInputStream(request.getInputStream());

    int formDataLength = request.getContentLength();
    byte dataBytes[] = new byte[formDataLength];
    int byteRead = 0;
    int totalBytesRead = 0;

    while (totalBytesRead < formDataLength) 
    {
        byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
        totalBytesRead += byteRead;
    }

    String file = new String(dataBytes);

    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;

    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;
    saveFile="http://hpws1/shared_mxd/pdf/" + saveFile;

    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

按名称上传文件:         &lt;%out.println(saveFile); %GT; &LT;%         }         %GT;

其中“saveFile =”http:// hpws1 / shared_mxd / pdf /“+ saveFile;”是服务器的路径。 但浏览器无法识别此路径,并显示错误“文件名,目录名称或卷标语法不正确”。 我怎么解决dis ???

1 个答案:

答案 0 :(得分:0)

为什么不使用表单发送文件?像这样:

<FORM ENCTYPE='multipart/form-data'
 method='POST' action='/myservlet'>
<INPUT TYPE='file' NAME='mptest'>
<INPUT TYPE='submit' VALUE='upload'>
</FORM>