文件上传服务器

以图片为例:

服务器代码:
在web3.1下,接受文件数据异常简单;

@WebServlet(name = "Upload",urlPatterns = "/Upload")
@MultipartConfig(location = "/media/su/4881FBF83BCC3475")
public class Upload extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Part part = request.getPart("file");
        part.write("Sky.jpg");   //主要代码

        response.setCharacterEncoding("UTF-8");

        PrintWriter out = response.getWriter();
        System.out.println("sdffsdfsdfsd");

        out.print("uploading success");
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
       doGet(request,response);
    }
<form method="POST" action="Upload" enctype="multipart/form-data">
    <input type="file" name="file"/><br>
    <input type="submit" value="submit"/><br>
  </form>

文件上传服务器的时候, 用浏览器可以查看相关上传数据;

------WebKitFormBoundaryeZIyMszhJhkT1hn0
Content-Disposition: form-data; name="file"; filename="YHK2.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryeZIyMszhJhkT1hn0--

上面是浏览器上面显示的数据;在下面的客服端上面很有用。

客服端,

1,对头文件进行拼装

String boundary = "------WebKitFormBoundaryeZIyMszhJhkT1hn0";
        String prefix = "--";
        String end = "\r\n";

2,设置网络配置

 URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();

            conn.setReadTimeout(5000);
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);

3,对发出的数据进行封装(处理)—头文件header

 conn.setRequestProperty("Content-Type",
                    "multipart/form-data;boundary=" + boundary);
            DataOutputStream out = new
                    DataOutputStream(conn.getOutputStream());
            out.writeBytes(prefix + boundary + end);
            out.writeBytes("Content-Disposition: form-data; " +
                    "name=\"file\"; filename=\"" + "70.jpg" + "\"" + end);
            out.writeBytes(end);

4,对发送出去的正文进行读取后发送

FileInputStream fileInputStream = new FileInputStream(
                    new File(fileName)
            );
            byte[] b =new byte[1024 * 4];
            int len;
            while ((len = fileInputStream.read()) != -1) {
                out.write(b, 0, len);
            }

            out.writeBytes(end);

            out.writeBytes(prefix + boundary + prefix + end);
        out.flush();

5,获取服务器返回的数据

BufferedReader reader = new BufferedReader(
                    new InputStreamReader(conn.getInputStream())
            );
            StringBuffer sb = new StringBuffer();
            String str;
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            System.out.println("====response====" + sb.toString());

6,关闭资源

 if (out != null) {
                out.close();
            }
            if (reader != null) {
                reader.close();
            }
 String url="http://10.10.39.11:8080/upload/Upload";
                File file = Environment.getExternalStorageDirectory();
                File fileAbs = new File(file, "70.jpg");

                String fileName=fileAbs.getAbsolutePath();
                UploadThread thread = new UploadThread(
                    url,fileName
                ); thread.start();

7,需要的相关权限:

<uses-permission android:name="android.permission.INTERNET" />

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
------WebKitFormBoundaryeZIyMszhJhkT1hn0
Content-Disposition: form-data; name="file"; filename="YHK2.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryeZIyMszhJhkT1hn0--

这段代码很重要,在客服端里面,连接服务器的时候,很重要,错一点点都不会成功。在34步骤中,一定要注意,少个回车或者上面都是不可以的。

你可能感兴趣的:(android)