1. 程式人生 > >使用springmvc 和nginx 搭建一個檔案上傳下載伺服器

使用springmvc 和nginx 搭建一個檔案上傳下載伺服器

public final class FileUploadUtil {

    public static JSONObject upload(String httpurl, String fileName, InputStream inputStream) {
        String result = "";
        try {

            String BOUNDARY = "---------7d4a6d158c9"; // 定義資料分隔線
            URL url = new URL(httpurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 傳送POST請求必須設定如下兩行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定義最後資料分隔線
            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"file" + 1
                    + "\";filename=\"" + fileName + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] data = sb.toString().getBytes();
            out.write(data);
            DataInputStream in = new DataInputStream(inputStream);
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.write("\r\n".getBytes()); // 多個檔案時,二個檔案之間加入這個
            in.close();
            out.write(end_data);
            out.flush();
            out.close();
            // 定義BufferedReader輸入流來讀取URL的響應
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));
            String line = null;
            while ((line = reader.readLine()) != null) {
                result+=line;
            }
        } catch (Exception e) {
            System.out.println("傳送POST請求出現異常!" + e);
        }
        return  JSONObject.parseObject(result);
    }

    public static void main(String[] args) throws Exception {
        String content ="hellow 中國";
        InputStream ips = new ByteArrayInputStream(content.getBytes("UTF-8"));
        System.out.println(upload("http://192.168.9.21:8082/fileShare/upload","text.txt",ips));

    }
}