关闭

上传文件

287人阅读 评论(0) 收藏 举报
分类:

第一种URLConnection

	public static synchronized String  upload(File file,String cookie,int index,String urlApi){
		    String contentType = FileUtils.getContentType(file.getName());
		    StringBuilder response = new StringBuilder();
		    HttpURLConnection conn = null;
	        OutputStream dos = null;
	        DataInputStream inStream = null;
	        String existingFileName = file.getAbsolutePath();
	        String lineEnd = "\r\n"; 
	        int bytesRead, bytesAvailable, bufferSize;
	        byte[] buffer;
	        int maxBufferSize = 1024; 
	        String urlString = urlApi;
	      
	        try{
	            //------------------ CLIENT REQUEST
	            FileInputStream fileInputStream = new FileInputStream(file); 
	            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. 
	            //skin=H; Coremail=9fbd0ad4f4cc4a93; CoremailReferer=https%3A%2F%2Fmail.yutong.com%2Fcoremail%2F; Coremail.sid=CAHmOeOOibihSovUSeOOTALFzmBJXqKf
	            String BOUNDARY = "---------------------------7d4a6d158c9"; // 分隔符  
                conn.setRequestMethod("POST");
	            conn.addRequestProperty("Connection", "Keep-Alive"); 
	            conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY); //设置表单类型和分隔符  
	            conn.addRequestProperty("Accept-Encoding", "gzip, deflate");
	            conn.addRequestProperty("Accept-Language", "zh-cn,zh;q=0.8,en-us;q=0.5,en;q=0.3");
	            conn.addRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
	            conn.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 5.1; rv:24.0) Gecko/20100101 Firefox/24.0");
	            conn.addRequestProperty("Cookie", cookie);  
	            dos =   conn.getOutputStream() ;
//	            
	            /************************/
	            
	            StringBuffer sb = new StringBuffer();  
	            sb.append("--");  
	            sb.append(BOUNDARY);  
	            sb.append("\r\n");  
	            sb.append("Content-Disposition: form-data; name=\"localAttach"+index+"\"; filename=\""+file.getName()+"\""+lineEnd);  
	            sb.append("Content-Type: "+contentType+"\r\n\r\n");  
	            byte[] data = sb.toString().getBytes();  
	            
	            
	            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes(); 
	           
	            dos.write(data); 
	            
	            bytesAvailable = fileInputStream.available();
	            bufferSize = Math.min(bytesAvailable, maxBufferSize);
	            buffer = new byte[bufferSize]; 
	            while ((bytesRead = fileInputStream.read(buffer, 0, bufferSize)) > 0){
	                dos.write(buffer, 0, bufferSize);  
	            } 
	            
	            dos.write(end_data); 
	            dos.flush();
	            dos.close();
	            fileInputStream.close();
	        }
	        catch (MalformedURLException e){
	            e.printStackTrace();
	        }
	        catch (IOException e){
	            e.printStackTrace();
	        }
	        
	        try {
	            inStream = new DataInputStream (conn.getInputStream() );
	            byte[] inbuf = new byte[1024];  
	            int rn;  
	            
	            while((rn=inStream.read(inbuf,0,1024))>0)  
	            {      
	                response.append(new String(inbuf,0,rn));
	            }  
	            inStream.close();  
	        }
	        catch (IOException ioex){
	           ioex.printStackTrace();
	        }
			return response.toString();
	       
	}
第二种MultipartEntity+HttpClient

class MultipartEntity implements HttpEntity { 
    private final static char[] MULTIPART_CHARS = "-_1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
    private String boundary = null; 
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    boolean isSetLast = false;
    boolean isSetFirst = false; 
    public MultipartEntity() {//在构造方法里创建一个随机的Boundary
        final StringBuffer buf = new StringBuffer();
        final Random rand = new Random();
        for (int i = 0; i < 30; i++) {
            buf.append(MULTIPART_CHARS[rand.nextInt(MULTIPART_CHARS.length)]);
        }
        this.boundary = buf.toString(); 
    }

    /**
     * 写头
     */
    public void writeFirstBoundaryIfNeeds(){
        if(!isSetFirst){
            try {
                out.write(("--" + boundary + "\r\n").getBytes());
            } catch (final IOException e) {
                e.printStackTrace();
            }
        } 
        isSetFirst = true;
    }

    /**
     * 写尾
     */
    public void writeLastBoundaryIfNeeds() {
        if(isSetLast){
            return;
        } 
        try {
            out.write(("\r\n--" + boundary + "--\r\n").getBytes());
        } catch (final IOException e) {
            e.printStackTrace();
        } 
        isSetLast = true;
    }

    
    
    public void addPart(final String key, final String value) {
        writeFirstBoundaryIfNeeds();
        try {
            out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n\r\n").getBytes());
            out.write(value.getBytes());
            out.write(("\r\n--" + boundary + "\r\n").getBytes());
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    public void addPart(final String key, final String fileName, final InputStream fin, final boolean isLast){
        addPart(key, fileName, fin, "application/octet-stream", isLast);
    }
     
  
    public void addPart(final String key, final String fileName, final InputStream fin, String type, final boolean isLast){
        writeFirstBoundaryIfNeeds();
        try {
            type = "Content-Type: "+type+"\r\n";
            out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
            out.write(type.getBytes());
            out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes()); 
            final byte[] tmp = new byte[4096];
            int l = 0;
            while ((l = fin.read(tmp)) != -1) {
                out.write(tmp, 0, l);
            }
            if(!isLast)
                out.write(("\r\n--" + boundary + "\r\n").getBytes());
            out.flush();
        } catch (final IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fin.close();
            } catch (final IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void addPart(final String key, final File value, final boolean isLast) {
        try {
            addPart(key, value.getName(), new FileInputStream(value), isLast);
        } catch (final FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    @Override
    public long getContentLength() {
        writeLastBoundaryIfNeeds();
        return out.toByteArray().length;
    }

    @Override
    public Header getContentType() {
        return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
    }

    @Override
    public boolean isChunked() {
        return false;
    }

    @Override
    public boolean isRepeatable() {
        return false;
    }

    @Override
    public boolean isStreaming() {
        return false;
    }

    @Override
    public void writeTo(final OutputStream outstream) throws IOException {
        outstream.write(out.toByteArray());
    }

    @Override
    public Header getContentEncoding() {
        return null;
    }

    @Override
    public void consumeContent() throws IOException,
    UnsupportedOperationException {
        if (isStreaming()) {
            throw new UnsupportedOperationException(
            "Streaming entity does not implement #consumeContent()");
        }
    }

    @Override
    public InputStream getContent() throws IOException,
    UnsupportedOperationException {
        return new ByteArrayInputStream(out.toByteArray());
    }
}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:42013次
    • 积分:636
    • 等级:
    • 排名:千里之外
    • 原创:1篇
    • 转载:121篇
    • 译文:0篇
    • 评论:0条