Creating file upload request using Java code

。_饼干妹妹 提交于 2020-02-05 08:58:30

问题


I want to implement a chat application in android.In my application I want to upload a file on server so I am using this code for listening file request on server side.

 protected void processRequest(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    // Create path components to save the file
    final String path = "/home/vibhor/vibhor";
    final Part filePart = request.getPart("file");
    final String fileName = getFileName(filePart);
    OutputStream out = null;
    InputStream filecontent = null;
    final PrintWriter writer = response.getWriter();
    try {
        out = new FileOutputStream(new File(path + File.separator
                + fileName));
        filecontent = filePart.getInputStream();

        int read = 0;
        final byte[] bytes = new byte[1024];

        while ((read = filecontent.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        writer.println("New file " + fileName + " created at " + path);
    } catch (FileNotFoundException fne) {
        writer.println("You either did not specify a file to upload or are "
                + "trying to upload a file to a protected or nonexistent "
                + "location.");
        writer.println("<br/> ERROR: " + fne.getMessage());

    } finally {
        if (out != null) {
            out.close();
        }
        if (filecontent != null) {
            filecontent.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

If I make a file request using HTML form like this then the above code works

<form action="UploadServlet" method="post"
                    enctype="multipart/form-data">
 <input type="file" name="file" size="50" />
 <br />
 <input type="submit" value="Upload File" />
 </form>

So I want to make the same request using the below code at client side(In android application)

public static void uploadFile(String selectedPath, String fileType,
        String fileName) {
    HttpURLConnection httpUrlConnection = null;
    DataOutputStream dataOutputStream = null;
    DataInputStream dataInputStream = null;
    String boundary = "*****";
    int bytesRead, bytesAvailable, bufferSize;
    byte[] buffer;
    int maxBufferSize = 1 * 1024 * 1024;
    String urlString = "http://localhost:8080/FileUploadServlet1/UploadServlet";
    File file = new File(selectedPath);
    try {
        FileInputStream fileInputStream = new FileInputStream(file);
        URL url = new URL(urlString);
        httpUrlConnection = (HttpURLConnection) url.openConnection();
        httpUrlConnection.setDoInput(true);
        httpUrlConnection.setConnectTimeout(50000000);
        httpUrlConnection.setDoOutput(true);
        httpUrlConnection.setUseCaches(false);
        httpUrlConnection.setChunkedStreamingMode(maxBufferSize);
        httpUrlConnection.setRequestMethod("POST");
        httpUrlConnection.setRequestProperty("Connection", "Keep-Alive");
        httpUrlConnection.setRequestProperty("Content-Type",
                "multipart/form-data;boundary=" + boundary);
        httpUrlConnection.setRequestProperty("filename", fileName);
        httpUrlConnection.setRequestProperty("filetype", fileType);

        dataOutputStream = new DataOutputStream(
                httpUrlConnection.getOutputStream());
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        buffer = new byte[bufferSize];
        int offset = 0;
        bytesRead = fileInputStream.read(buffer, offset, bufferSize);
        while (bytesRead > 0) {
            dataOutputStream.write(buffer, 0, bufferSize);
            bytesAvailable = fileInputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = fileInputStream.read(buffer, 0, bufferSize);
        }
        fileInputStream.close();
        dataOutputStream.flush();
        dataOutputStream.close();
    } catch (MalformedURLException ex) {
        ex.printStackTrace();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    try {
        dataInputStream = new DataInputStream(
                httpUrlConnection.getInputStream());
        dataInputStream.close();
    } catch (IOException ioex) {
        ioex.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

}

But in this case I am getting exception on this line

final String fileName = getFileName(filePart);

I have also used Apache file upload library but in that case also I got no value for this line

List fileItems = upload.parseRequest(request);

So what change should I do in uploadFile() method Please help.


回答1:


Here's the sample code which uploads file on server. You need external libraries to make this work like apache common, http mime and http core. Using external libraries the code is very easy to understand and clean.

public static String post(String url,String[] args) throws UnsupportedEncodingException {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);

        FileBody bin = new FileBody(new File(args[0]));//"/sdcard/DCIM/cam.jpg"));//
        long size = bin.getContentLength();

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("image1", bin);
        String content = "-";
        try {
             httpPost.setEntity(reqEntity);
                HttpResponse response = httpClient.execute(httpPost, localContext);
                HttpEntity ent = response.getEntity();
                InputStream st = ent.getContent();
                StringWriter writer = new StringWriter();
                IOUtils.copy(st, writer);
                content = writer.toString();                

        } catch (IOException e) {                   
            return "false";
        }
        return content;
    }


来源:https://stackoverflow.com/questions/17759075/creating-file-upload-request-using-java-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!