1

我一直在尝试通过 servlet 将文件上传到 Tomcat 服务器,但没有成功。我能够创建一个目录,但不知何故,servlet 代码没有在“上传”目录中创建一个文件。

Android中的Java代码:

 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);
     }
}

Tomcat 服务器上的 Servlet 代码:

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);
 }
}

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

/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
4

1 回答 1

1

你的Content-Disposition标题是错误的。它说post-data虽然它必须form-data以防万一multipart/form-data。在您的客户端中相应地修复它:

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

也可以看看:


与具体问题无关,将上传的文件存储在 webapp 的部署文件夹中绝对是个坏主意。每当您重新部署 webapp 的新版本时,它们都会丢失,原因很简单,到目前为止所有上传的文件肯定不包含在原始 WAR 中。将它们存储在部署文件夹之外的其他位置。只是永远不要使用getRealPath(),它只会导致不良做法。

此外,FileInputStream#available()绝对不会按照您在代码中的想法进行操作。摆脱它,只需在具有固定缓冲区大小(例如 10KB)的 for 循环中执行通常的读写操作。

此外,DataOutputStream在这里使用是可怕的。它有不同的用途(创建.dat文件),在这个特定的结构中,字符编码相关问题存在很大风险。只需使用带有指定字符集的PrintWriter环绕即可。OutputStreamWriter请注意,上面的“另请参阅”链接中显示了一个完整的示例。

于 2012-11-29T01:34:46.477 回答