无法通过servlet的code上传Tomcat服务器上的文件 [英] Not able to upload file on tomcat server through servlet code

查看:328
本文介绍了无法通过servlet的code上传Tomcat服务器上的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在试图通过一个se​​rvlet上传文件到Tomcat服务器,但没有成功。我可以创建目录,但不知何故该servlet code未创造上载目录中的文件。

Java的code在Android的:

 公共无效上传()
{
     字符串exsistingFileName =路径+//+test123.txt     字符串lineEnd =\\ r \\ n;
     串twoHyphens = - ;
     字符串边界=*****;
     尝试{
         // ------------------客户端请求         Log.e(标签,内部第二种方法);         的FileInputStream的FileInputStream =新的FileInputStream(新文件(
                 exsistingFileName));         //打开一个URL连接到这个Servlet         网址URL =新的URL(urlString);         //打开HTTP连接的URL         康恩=(HttpURLConnection类)url.openConnection();         //允许输入
         conn.setDoInput(真);         //允许输出
         conn.setDoOutput(真);         //不要使用缓存副本。
         conn.setUseCaches(假);         //使用POST方法。
         conn.setRequestMethod(POST);         conn.setRequestProperty(连接,保持活动);         conn.setRequestProperty(内容类型,
                的multipart / form-data的;边界=+边界);
         DataOutputStream类DOS =新的DataOutputStream类(conn.getOutputStream());         dos.writeBytes(twoHyphens +边界+ lineEnd);
         dos.writeBytes(内容处置:后数据; NAME = UploadedFile的;文件名=
                         + exsistingFileName ++ lineEnd);
         dos.writeBytes(lineEnd);         Log.e(标签,头信息);         //创建最大大小的缓冲区         INT参考bytesAvailable = fileInputStream.available();
         INT MAXBUFFERSIZE = 1000;
         // INT缓冲区大小= Math.min(方bytesAvailable,MAXBUFFERSIZE);
         字节[]缓冲区=新的字节[方bytesAvailable]         //读取文件,并将其写入形式...         INT读取动作= fileInputStream.read(缓冲液,0,参考bytesAvailable);         而(读取动作大于0){
             dos.write(缓冲液,0,参考bytesAvailable);
             参考bytesAvailable = fileInputStream.available();
             参考bytesAvailable = Math.min(方bytesAvailable,MAXBUFFERSIZE);
             读取动作= fileInputStream.read(缓冲液,0,参考bytesAvailable);
         }         //发送文件数据后necesssary多部分的表单数据...         dos.writeBytes(lineEnd);
         dos.writeBytes(twoHyphens +边界+ twoHyphens + lineEnd);         //关闭流
         Log.e(标签,文件写入);
         fileInputStream.close();
         dos.flush();
         dos.close();     }赶上(MalformedURLException的前){
         Log.e(标签,错误:+ ex.getMessage(),除息);
     }     赶上(IOException异常IOE){
         Log.e(标签,错误:+ ioe.getMessage(),IOE);
     }     尝试{
         RD的BufferedReader =新的BufferedReader(新的InputStreamReader(康恩
                 .getInputStream()));
         串线;
         而((行= rd.readLine())!= NULL){
             Log.e(Dialoge箱,消息:+线);
         }
         rd.close();     }赶上(IOException异常ioex){
         Log.e(MediaPlayer的,错误:+ ioex.getMessage(),ioex);
     }
}

Tomcat服务器上的Servlet code:

 进口的java.io.File;
进口java.io.IOException异常;
进口java.util.Iterator的;
进口的java.util.List;进口javax.servlet.ServletException;
进口javax.servlet.http.HttpServlet;
进口javax.servlet.http.HttpServletRequest;
进口javax.servlet.http.HttpServletResponse;进口org.apache.commons.fileupload.FileItem的;
进口org.apache.commons.fileupload.disk.DiskFileItemFactory;
进口org.apache.commons.fileupload.servlet.ServletFileUpload;/ **
* Servlet实现类UploadServlet
* /
公共类UploadServlet延伸的HttpServlet {
私有静态最后的serialVersionUID长1L =;私有静态最后弦乐UPLOAD_DIRECTORY =上载;
私有静态最终诠释THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
私有静态最终诠释MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
私有静态最终诠释REQUEST_SIZE = 1024 * 1024 * 50; // 50MB/ **
 * @see的HttpServlet#的doPost(HttpServletRequest的请求,HttpServletResponse的
 *响应)
 * /
 保护无效的doPost(HttpServletRequest的请求,
        HttpServletResponse的响应)抛出了ServletException,IOException异常{
    //检查请求是否实际上包含上传文件
    如果(!ServletFileUpload.isMultipartContent(要求)){
        //如果没有,我们停在这里
        返回;
    }    //配置一些设置
    DiskFileItemFactory厂=新DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(新文件(System.getProperty(java.io.tmpdir)));    ServletFileUpload上传=新ServletFileUpload(工厂);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);    //构造来存储上传文件的目录路径
    串uploadPath = getServletContext()方法。getRealPath()
        +文件分割符+ UPLOAD_DIRECTORY;
    //创建目录,如果它不存在,
    文件uploadDir =新的文件(uploadPath);
    如果(!uploadDir.exists()){
        uploadDir.mkdir(); //我可以看到创建的目录...但创建目录之后后没有任何反应....没有错误消息显示
    }    尝试{
        //解析请求的内容提取文件数据
        清单formItems = upload.parseRequest(请求);
        ITER的Iterator = formItems.iterator();        //重于形式的迭代领域
        而(iter.hasNext()){
            的FileItem项目=(的FileItem)iter.next();
            //只处理未形成字段的字段
            如果(!item.isFormField()){
                字符串文件名=新的文件(item.getName())的getName()。
                字符串文件路径= uploadPath +文件分割符+文件名;
                文件storeFile =新的文件(文件路径);                //保存磁盘上的文件
                item.write(storeFile);
            }
        }
        了request.setAttribute(信息,上传已成功完成!);
    }赶上(例外前){
        了request.setAttribute(信息,有一个错误:+ ex.getMessage());
    }
    。getServletContext()方法的getRequestDispatcher(/ message.jsp)向前(请求,响应)。
 }
}

在服务器上我的文件结构是:

/ webapps /下
   演示/
      上传/ - 我试图创建(test123.txt)文件应该是这个文件夹中,但它不是。
   WEB-INF /
      类/ - UploadServlet.class
      LIB / - 公地IO和上载罐


解决方案

内容处置头是错误的。它说后数据,同时它必须是多部分的情况下,表单数据 /表单数据。在客户端相应的修正:

  dos.writeBytes(内容处置:表格数据;名称= UploadedFile的;文件名=
                     + exsistingFileName ++ lineEnd);

参见:


无关的具体问题,存储在webapp的部署文件夹上传的文件绝对是一个坏主意。他们都会迷路,只要你重新部署web应用程序的新版本,与理由很简单,所有这些,到目前为止上传的文件是肯定不包含在原始WAR。将它们储存在其他地方部署文件夹之外。只是不要用不完 getRealPath(),它只会导致糟糕的做法。

此外,的FileInputStream#可用()绝对不会做你在code觉得有什么。摆脱它,只是做平常读写在for循环中具有固定的缓冲区大小,例如10KB。

此外,使用 DataOutputStream类这里是可怕的。它服务于不同目的(创建 .DAT 文件),并在这个特殊的构造有字符编码相关的问题一个很大的风险。只需使用的PrintWriter 您环绕 OutputStreamWriter 用指定的字符集。需要注意的是一个完整的例子在上面显示另见链接。

I have been trying to upload a file to a Tomcat server through a servlet, but without success. I am able to create a directory, but somehow the servlet code is not creating a file inside the "upload" directory.

Java code in Android:

 public void upLoad()
{


     String exsistingFileName = path+"//"+"test123.txt";

     String lineEnd = "\r\n";
     String twoHyphens = "--";
     String boundary = "*****";
     try {
         // ------------------ CLIENT REQUEST

         Log.e(Tag, "Inside second Method");

         FileInputStream fileInputStream = new FileInputStream(new File(
                 exsistingFileName));

         // open a URL connection to the Servlet

         URL url = new URL(urlString);

         // Open a HTTP connection to the URL

         conn = (HttpURLConnection) url.openConnection();

         // Allow Inputs
         conn.setDoInput(true);

         // Allow Outputs
         conn.setDoOutput(true);

         // Don't use a cached copy.
         conn.setUseCaches(false);

         // Use a post method.
         conn.setRequestMethod("POST");

         conn.setRequestProperty("Connection", "Keep-Alive");

         conn.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);


         DataOutputStream dos = new DataOutputStream(conn.getOutputStream());

         dos.writeBytes(twoHyphens + boundary + lineEnd);
         dos.writeBytes("Content-Disposition: post-data; name=uploadedfile;filename="
                         + exsistingFileName + "" + lineEnd);
         dos.writeBytes(lineEnd);

         Log.e(Tag, "Headers are written");

         // create a buffer of maximum size

         int bytesAvailable = fileInputStream.available();
         int maxBufferSize = 1000;
         // int bufferSize = Math.min(bytesAvailable, maxBufferSize);
         byte[] buffer = new byte[bytesAvailable];

         // read file and write it into form...

         int bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);

         while (bytesRead > 0) {
             dos.write(buffer, 0, bytesAvailable);
             bytesAvailable = fileInputStream.available();
             bytesAvailable = Math.min(bytesAvailable, maxBufferSize);
             bytesRead = fileInputStream.read(buffer, 0, bytesAvailable);
         }

         // send multipart form data necesssary after file data...

         dos.writeBytes(lineEnd);
         dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

         // close streams
         Log.e(Tag, "File is written");
         fileInputStream.close();
         dos.flush();
         dos.close();

     } catch (MalformedURLException ex) {
         Log.e(Tag, "error: " + ex.getMessage(), ex);
     }

     catch (IOException ioe) {
         Log.e(Tag, "error: " + ioe.getMessage(), ioe);
     }

     try {
         BufferedReader rd = new BufferedReader(new InputStreamReader(conn
                 .getInputStream()));
         String line;
         while ((line = rd.readLine()) != null) {
             Log.e("Dialoge Box", "Message: " + line);
         }
         rd.close();

     } catch (IOException ioex) {
         Log.e("MediaPlayer", "error: " + ioex.getMessage(), ioex);
     }
}

Servlet code on Tomcat server:

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
* Servlet implementation class UploadServlet
*/
public class UploadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private static final String UPLOAD_DIRECTORY = "upload";
private static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 *      response)
 */
 protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    // checks if the request actually contains upload file
    if (!ServletFileUpload.isMultipartContent(request)) {
        // if not, we stop here
        return;
    }

    // configures some settings
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("")
        + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();   //I can see the created directory...but nothing happens after that....No error message display after creating directory
    }

    try {
        // parses the request's content to extract file data
        List formItems = upload.parseRequest(request);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
            }
        }
        request.setAttribute("message", "Upload has been done successfully!");
    } catch (Exception ex) {
        request.setAttribute("message", "There was an error: " + ex.getMessage());
    }
    getServletContext().getRequestDispatcher("/message.jsp").forward(request,         response);
 }
}

My file structure on the server is:

/webapps/
   demo/
      upload/ - The file I'm trying to create (test123.txt) should be inside this folder, but it's not.
   WEB-INF/
      classes/ - UploadServlet.class
      lib/ - commons IO and upload jars

解决方案

Your Content-Disposition header is wrong. It says post-data while it has to be form-data in case of multipart/form-data. Fix it accordingly in your client:

dos.writeBytes("Content-Disposition: form-data; name=uploadedfile;filename="
                     + exsistingFileName + "" + lineEnd);

See also:


Unrelated to the concrete problem, storing uploaded files in the webapp's deploy folder is absolutely a bad idea. They'll all get lost whenever you redeploy a new version of the webapp, with the simple reason that all those so far uploaded files are for sure not contained in the original WAR. Store them somewhere else outside the deploy folder. Just do not ever use getRealPath(), it'll only lead to poor practices.

Further, FileInputStream#available() absolutely doesn't do what you thought there in your code. Get rid of it and just do the usual read-write in a for loop with a fixed buffer size, e.g. 10KB.

Also, using DataOutputStream here is scary. It serves a different purpose (creating .dat files) and in this particular construct there's a big risk for character encoding related issues. Just use PrintWriter which you wrap around OutputStreamWriter with a specified charset. Note that a complete example is shown in the above "See also" link.

这篇关于无法通过servlet的code上传Tomcat服务器上的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆