All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.mycomm.YesHttp.core.FileUploadRequest Maven / Gradle / Ivy

/*
 * Copyright 2018 jw362j.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.mycomm.YesHttp.core;

import com.mycomm.YesHttp.comm.MyConstant;
import com.mycomm.YesHttp.util.MimeTypeMapping;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLConnection;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author jw362j
 */
public abstract class FileUploadRequest extends BaseRequest {

    private byte[] headerInfo;
    private byte[] endInfo;
    private File uploadFile;
    private String FormFileFieldName;
    private Response.DownLoadUpLoadListener upLoadListener;
    private long fileContentLength;

    private final HttpObserver observer = new HttpObserver() {
        public void Observe(URLConnection connection) {

            if (Method.POST != getmMethod()) {
                return;
            }
            try {
                uploadFile = getUploadFile();
                String newFileName = uploadFile.getName();
                StringBuilder sb = new StringBuilder();
                fileContentLength = uploadFile.length();
                /**
                 * 普通的表单数据
                 */
                Map params = getParams();
                if (params != null) {
                    for (String key : params.keySet()) {
                        sb.append("--" + BOUNDARY + "\r\n");
                        sb.append("Content-Disposition: form-data; name=\"").append(key).append("\"" + "\r\n");
                        sb.append("\r\n");
                        sb.append(params.get(key)).append("\r\n");
                    }
                }

                /**
                 * 上传文件的头
                 */
                sb.append("--" + BOUNDARY + "\r\n");
                if(FormFileFieldName == null || "".equals(FormFileFieldName)){
                    FormFileFieldName = "uploadImage";
                }
                sb.append("Content-Disposition: form-data; name=\"").append(FormFileFieldName).append("\"; filename=\"").append(newFileName).append("\"").append("\r\n");
                String mimeType =  MimeTypeMapping.getMimeType(uploadFile.getName());
                if(mimeType == null || "".equals(mimeType)){
                    mimeType = "text/plain";
                }                
                sb.append("Content-Type: ").append(mimeType).append("\r\n");// 如果服务器端有文件类型的校验,必须明确指定ContentType
                sb.append("\r\n");
                getLog().LogMe("the headerInfo in  FileUploadRequest is:" + sb.toString());
                headerInfo = sb.toString().getBytes("UTF-8");
                endInfo = ("\r\n--" + BOUNDARY + "--\r\n").getBytes("UTF-8");
                // 设置传输内容的格式,以及长度
                connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
                connection.setRequestProperty("Content-Length",
                        String.valueOf(headerInfo.length + uploadFile.length() + endInfo.length));
            } catch (UnsupportedEncodingException ex) {
                Logger.getLogger(FileUploadRequest.class.getName()).log(Level.SEVERE, null, ex);
            }

        }
    };
    private static final String BOUNDARY = "----WebKitFormBoundaryT1HoybnYeFOGFlBR";

    public FileUploadRequest(String mUrl, Response.Listener response, HttpObserver observer, Response.ErrorListener errorListener, YesLog log, short protocol, Response.DownLoadUpLoadListener listener) {
        this(mUrl, response, observer, errorListener, log, protocol, listener, null);
    }

    public FileUploadRequest(String mUrl, Response.Listener response, HttpObserver observer, Response.ErrorListener errorListener, YesLog log, short protocol, Response.DownLoadUpLoadListener listener, String formFileFieldName) {
        super(Request.Method.POST, mUrl, response, observer, errorListener, log, protocol);
        this.upLoadListener = listener;
        this.FormFileFieldName = formFileFieldName;
    }

    @Override
    public HttpObserver getHttpObserver() {
        return observer;
    }

    public void write(OutputStream outputStream) {
        InputStream in = null;
        try {
            if (Method.POST != getmMethod()) {
                return;
            }
            in = new FileInputStream(uploadFile);
            // 写入头部 (包含了普通的参数,以及文件的标示等)
            outputStream.write(headerInfo);
            // 写入文件
            byte[] buf = new byte[1024];
            int len;
            long savedLength = 0;
            float rate_;
            float lastRate = 0f; 
            float rateDiffer ;
            while ((len = in.read(buf)) != -1) {
                savedLength += len;
                outputStream.write(buf, 0, len);
                if (this.upLoadListener != null) {
                    rate_ = ((float) savedLength / (float) fileContentLength);
                    rateDiffer = rate_ - lastRate;
                      if(rateDiffer >= MyConstant.refRate){
                          this.upLoadListener.onProgressing(rate_);
                          lastRate = rate_;
                      }                    
                }
            }

            // 写入尾部
            outputStream.write(endInfo);
        } catch (FileNotFoundException ex) {
            getLog().LogMe("error happen in A01" + ex.getMessage());
        } catch (IOException ex) {
            getLog().LogMe("error happen in A02" + ex.getMessage());
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                getLog().LogMe("error happen in A03" + ex.getMessage());
            }
        }
    }
    
    public abstract File getUploadFile();

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy