一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務(wù)器之家 - 編程語言 - JAVA教程 - formfile文件上傳使用示例

formfile文件上傳使用示例

2019-11-13 12:48java教程網(wǎng) JAVA教程

這篇文章主要介紹了formfile文件上傳使用示例,代碼已加注釋,需要的朋友可以參考下

代碼如下:


package TOOLS;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.util.Map;
import android.util.Log;

 

/**
 * 上傳的文件
 */
public class FormFile {
    private final static String LOGKEY = "FormFile";
    /** 上傳文件的數(shù)據(jù) */
    private byte[] data;
    private InputStream inStream;
    private File file;
    /** 文件名稱 */
    private String filname;
    /** 請求參數(shù)名稱 */
    private String parameterName;
    /** 內(nèi)容類型 */
    private String contentType = "application/octet-stream";

    /**
     * 
     * @param filname
     *            文件名稱
     * @param data
     *            上傳的文件數(shù)據(jù)
     * @param parameterName
     *            參數(shù)
     * @param contentType
     *            內(nèi)容類型
     */
    public FormFile(String filname, byte[] data, String parameterName,
            String contentType) {
        this.data = data;
        this.filname = filname;
        this.parameterName = parameterName;
        if (contentType != null)
            this.contentType = contentType;
    }

    /**
     * 
     * @param filname
     *            文件名
     * @param file
     *            上傳的文件
     * @param parameterName
     *            參數(shù)
     * @param contentType
     *            內(nèi)容內(nèi)容類型
     */
    public FormFile(String filname, File file, String parameterName,
            String contentType) {
        this.filname = filname;
        this.parameterName = parameterName;
        this.file = file;
        try {
            this.inStream = new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        if (contentType != null)
            this.contentType = contentType;
    }

    public File getFile() {
        return file;
    }

    public InputStream getInStream() {
        return inStream;
    }

    public byte[] getData() {
        return data;
    }

    public String getFilname() {
        return filname;
    }

    public void setFilname(String filname) {
        this.filname = filname;
    }

    public String getParameterName() {
        return parameterName;
    }

    public void setParameterName(String parameterName) {
        this.parameterName = parameterName;
    }

    public String getContentType() {
        return contentType;
    }

    public void setContentType(String contentType) {
        this.contentType = contentType;
    }
    private String Opertype=null;
    public void setOper(String Opertype){
        this.Opertype=Opertype;
    }
    public boolean post(String path, Map<String, String> params)
            throws Exception {
        final String BOUNDARY = "--------------7da2137580612"; // 數(shù)據(jù)分隔線
        final String endline = "--" + BOUNDARY + "--\r\n";// 數(shù)據(jù)結(jié)束標志

        int fileDataLength = 0;
        // 得到文件類型數(shù)據(jù)的總長度
        StringBuilder fileExplain = new StringBuilder();
        fileExplain.append("--");
        fileExplain.append(BOUNDARY);
        fileExplain.append("\r\n");
        fileExplain.append("Content-Disposition: form-data;name=\""
                + getParameterName() + "\";filename=\"" + getFilname()
                + "\"\r\n");
        fileExplain.append("Content-Type: " + getContentType() + "\r\n\r\n");
        fileExplain.append("\r\n");
        fileDataLength += fileExplain.length();
        if (getInStream() != null) {
            fileDataLength += getFile().length();
        } else {
            fileDataLength += getData().length;
        }

        StringBuilder textEntity = new StringBuilder();
        for (Map.Entry<String, String> entry : params.entrySet()) {//構(gòu)造文本類型參數(shù)的實體數(shù)據(jù)
            textEntity.append("--");
            textEntity.append(BOUNDARY);
            textEntity.append("\r\n");
            textEntity.append("Content-Disposition: form-data; name=\""
                    +  entry.getKey() + "\"\r\n\r\n");
            textEntity.append(entry.getValue());
            textEntity.append("\r\n");
        }
        Log.v(LOGKEY, textEntity.toString());
        // 計算傳輸給服務(wù)器的實體數(shù)據(jù)總長度
        int dataLength = textEntity.toString().getBytes().length
                + fileDataLength + endline.getBytes().length;

        URL url = new URL(path);
        Log.v(LOGKEY, url.toString());
        int port = url.getPort() == -1 ? 80 : url.getPort();
        Socket socket = new Socket(InetAddress.getByName(url.getHost()), port);
        OutputStream outStream = socket.getOutputStream();
        // 下面完成HTTP請求頭的發(fā)送
        String requestmethod = "POST " + url.getPath()+"?"+Opertype + " HTTP/1.1\r\n";
        Log.v(LOGKEY, requestmethod);
        outStream.write(requestmethod.getBytes());
        String accept = "Accept: image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*\r\n";
        outStream.write(accept.getBytes());
        String language = "Accept-Language: zh-CN\r\n";
        outStream.write(language.getBytes());
        String contenttype = "Content-Type: multipart/form-data; boundary="
                + BOUNDARY + "\r\n";
        outStream.write(contenttype.getBytes());
        String contentlength = "Content-Length: " + dataLength + "\r\n";
        outStream.write(contentlength.getBytes());
        String alive = "Connection: Keep-Alive\r\n";
        outStream.write(alive.getBytes());
        String host = "Host: " + url.getHost() + ":" + port + "\r\n";
        outStream.write(host.getBytes());
        // 寫完HTTP請求頭后根據(jù)HTTP協(xié)議再寫一個回車換行
        outStream.write("\r\n".getBytes());
        // 把所有文本類型的實體數(shù)據(jù)發(fā)送出來
        outStream.write(textEntity.toString().getBytes());
        // 把所有文件類型的實體數(shù)據(jù)發(fā)送出來

        StringBuilder fileEntity = new StringBuilder();
        fileEntity.append("--");
        fileEntity.append(BOUNDARY);
        fileEntity.append("\r\n");
        fileEntity.append("Content-Disposition: form-data;name=\""
                + getParameterName() + "\";filename=\"" + getFilname()
                + "\"\r\n");
        fileEntity.append("Content-Type: " + getContentType() + "\r\n\r\n");
        outStream.write(fileEntity.toString().getBytes());
        if (getInStream() != null) {
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = getInStream().read(buffer, 0, 1024)) != -1) {
                outStream.write(buffer, 0, len);
            }
            getInStream().close();
        } else {
            outStream.write(getData(), 0, getData().length);
        }
        outStream.write("\r\n".getBytes());

        // 下面發(fā)送數(shù)據(jù)結(jié)束標志,表示數(shù)據(jù)已經(jīng)結(jié)束
        outStream.write(endline.getBytes());

        BufferedReader reader = new  BufferedReader(new InputStreamReader(socket.getInputStream()));
        if (reader.readLine().indexOf("200") == -1) {// 讀取web服務(wù)器返回的數(shù)據(jù),判斷請求碼是否為200,如果不是200,代表請求失敗
            return false;
        }

        outStream.flush();
        outStream.close();
        reader.close();
        socket.close();
        return true;
    }
}
//測試代碼
File iconFile = new File("file路徑");
String url="htttp://192.168.1.101:8080/APP/initServlet";
Map<String, String> map = new HashMap<String, String>();//表單內(nèi)容
map.put("name","blog");

if (iconFile != null) {
                    FormFile uploadfile = new FormFile(iconFile.getName(),
                            iconFile, "iconfile", "image/jpeg");
                    uploadfile.setOper("action=insertusr");//在url上插入?action=insertusr
                    try {
                        boolean isok = uploadfile.post(url, map);
                    } catch (Exception e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

 

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 青青操在线播放 | 波多在线 | 日本三级s级在线播放 | 免费高清资源黄网站在线观看 | 175m美女被网友灌醉啪啪玩脚 | 青青草99热久久 | 国产成人亚洲精品91专区手机 | 思思91精品国产综合在线 | 日本成人黄色网址 | 非洲黑人又大粗gay 非洲黑人bbwbbwbbw | 太大了轻点阿受不了小说h 四色6677最新永久网站 | 免费网站直接进入 | 亚飞与亚基国语1080p在线观看 | 日本成熟bbxxxxxxxx | 国产免费看黄的私人影院 | 日韩一级片在线播放 | 男女车车好快的车车免费网站 | 亚洲码在线观看 | 免费二区 | 香蕉久久一区二区不卡无毒影院 | 青草园网站在线观看 | 四虎精品在线视频 | 五月桃花网婷婷亚洲综合 | 桃乃木香奈ipx在线播放 | 特a级片 | 爽爽影院免费观看 | 9 1 视频在线 | 国产视频中文字幕 | 免费a视频在线观看 | 日本人在线看片 | 果冻传媒在线完整免费观 | 999久久久免费精品国产牛牛 | 国产精品天天影视久久综合网 | 日本一片免费观看高清完整 | 精品欧美男同同性videos | 丝瓜视频成人在线观看 | 亚洲视频在线免费 | 天选之王漫画顾长歌免费阅读 | 天堂伊人 | 四虎影院久久 | 欧美另类xxx精品人妖 |