从多部分格式获取文件内容

时间:2014-04-12 03:59:03

标签: java file-upload io inputstream multipartform-data

我想在这里做的是用户上传他的文件,我将把这个文件存储到我的服务器端

重要提示:我只能使用" servlet-api.jar(2.4版本)",我不能使用其他JAR!

我使用<form action=\"/Mapreduce/upload\" method=\"POST\" enctype=\"multipart/form-data\">上传文件。

然后我使用此代码InputStream whole = request.getInputStream();来获取整个输入流。

然后我使用此代码获取文件内容的字符串

BufferedReader br = new BufferedReader(new InputStreamReader(whole, "UTF-8"));
while ((line = br.readLine()) != null) {
      sb.append(line);// sb is stringbuilder here
}

然后,我将我从stringbuilder获得的字符串转换为InputStream:

InputStream is = new ByteArrayInputStream(result.getBytes("UTF-8""));

最后,我使用以下代码将此InputStream is写入另一个文件(temp):

OutputStream outputStream = new FileOutputStream(temp);// temp is a file.
int read = 0;
byte[] bytes = new byte[1024];
while ((read = is.read(bytes)) != -1) {
    outputStream.write(bytes, 0, read);
}

当我上传.txt文件时,它可以工作,我可以打开temp.txt。但是,当我上传.docx文件时,我无法打开temp.docx。我怎么解决这个问题?是因为我的编码错了吗?

2 个答案:

答案 0 :(得分:0)

你不需要做那么多事情。你可以这样做:

的index.html

<html>  
<body>  
<form action="go" method="post" enctype="multipart/form-data">  //here go is path for servelet
Select File:<input type="file" name="fname"/><br/>  
<input type="submit" value="upload"/>  
</form>  
</body>  
</html>  

UploadServlet.java

import java.io.*;  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
import com.oreilly.servlet.MultipartRequest;  

public class UploadServlet extends HttpServlet {  

public void doPost(HttpServletRequest request, HttpServletResponse response)  
    throws ServletException, IOException {  

response.setContentType("text/html");  
PrintWriter out = response.getWriter();  

MultipartRequest m=new MultipartRequest(request,"d:/new");  //d is directory to upload file
out.print("successfully uploaded");  
}  
}

web.xml文件

<web-app>  

<servlet>  
<servlet-name>UploadServlet</servlet-name>  
<servlet-class>UploadServlet</servlet-class>  
</servlet>  

<servlet-mapping>  
<servlet-name>UploadServlet</servlet-name>  
<url-pattern>/go</url-pattern>  
</servlet-mapping>  

</web-app>  

并从以下链接下载cos.jar文件:http://ftp.java2s.com/Code/Jar/c/Downloadcosmultipartjar.htm。并把它放到你的类路径。

答案 1 :(得分:-1)

您可以将您的Servlet代码编写为

Part filepart=request.getPart("file");
    System.out.println(filepart);
    String filename=null;
    if(filepart!=null){
        System.out.println("IF filepart not null");
        System.out.println(filepart.getName());
        System.out.println(filepart.getContentType());
        System.out.println(filepart.getSize());
        System.out.println(filepart.getInputStream());


               String contentDisp = filepart.getHeader("content-disposition");
               System.out.println("content-disposition header= "+contentDisp);
               String[] tokens = contentDisp.split(";");
              for (String token : tokens) {
                if (token.trim().startsWith("filename")) 
                System.out.println(token.substring(token.indexOf("=") + 2, token.length()-1));
            filename=token.substring(token.indexOf("=") + 2, token.length()-1);
            System.out.println("File Name New is: " +filename);            
    }           

    }   

    InputStream inputstream=null;
    if(filepart!=null)
    {
        inputstream=filepart.getInputStream();
        System.out.println("File data: " +inputstream);
    }

在这里您可以获得上传文件的文件名和内容。在此代码之后,您可以编写用于在DB或系统中存储文件的代码。