上传文件

转载 2013年12月06日 10:33:25

第一种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());
    }
}




相关文章推荐

struts文件上传

  • 2017年11月06日 14:47
  • 3KB
  • 下载

文件上传漏洞(绕过姿势)

文件上传漏洞可以说是日常渗透测试用得最多的一个漏洞,因为用它获得服务器权限最快最直接。但是想真正把这个漏洞利用好却不那么容易,其中有很多技巧,也有很多需要掌握的知识。俗话说,知己知彼方能百战不殆,因此...
  • zxchhyg
  • zxchhyg
  • 2017年06月01日 14:21
  • 1183

webuploader实现大文件分片上传

  • 2017年11月02日 10:07
  • 8KB
  • 下载

c#同时上传文件和参数

  • 2017年10月31日 15:40
  • 34KB
  • 下载

06_Java中文件上传与下载

文件上传的准备:1.表单中的enctype的值需要修改为:multipart/form-data 注意:修改之后,我们在Servlet就不能够再通过request.getParameter(S...

最好用的上传文件-uplodifive

  • 2017年11月20日 10:17
  • 63KB
  • 下载

Spring MVC文件上传

  • 2017年11月17日 23:50
  • 15.44MB
  • 下载

ajax异步上传文件/图片

JS前端 注意:ajaxFileUpload需要有jQuery的支持,所以这段JS代码需要放在引入的jQuery代码后面,或者放在$.ready(function(){})的方法里面,不然会报错 /...

文件上传的jar

  • 2017年11月15日 16:53
  • 217KB
  • 下载
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:上传文件
举报原因:
原因补充:

(最多只允许输入30个字)