Android_POST文件上传

1.servlet
public class NewsServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            if(ServletFileUpload.isMultipartContent(request)){
                FileItemFactory fileItemFactory=new DiskFileItemFactory();
                ServletFileUpload fileUpload=new ServletFileUpload(fileItemFactory);
                List<FileItem> items=fileUpload.parseRequest(request);
                String dir=request.getRealPath("upload");
                File dirFile=new File(dir);
                if(!dirFile.exists()) dirFile.mkdirs();
                for(FileItem item:items){
                    if(item.isFormField()){//表单字段
                        String name=item.getFieldName();
                        String value=item.getString();
                        System.out.println(name+"="+value);
                    }else{
                        String fileName=item.getName();
                        File saveFile=new File(dir+File.separator+fileName);
                        item.write(saveFile);
                        System.out.println(saveFile.getPath());
                    }
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

2.FormFile
public class FormFile {

    private byte[] data;
    private InputStream inputStream;
    private File file;
    private String filename;
    private String parameterName;
    private String contentType="application/octet-stream";
    
    //直接奖文件读到内存中,适合小文件上传
    public FormFile(String filename,byte[] data,String parameterName,String contentType) {
        this.data=data;
        this.filename=filename;
        this.parameterName=parameterName;
        if(contentType!=null) 
            this.contentType=contentType;
    }
    
    //文件对象,适合大文件上传,边传边读
    public FormFile(File file,String parameterName,String contentType) {
        this.filename=file.getName();
        this.parameterName=parameterName;
        this.file=file;
        try {
            this.inputStream=new FileInputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }
}
3.POST file
ViedoService
//手动POST上传文件
    public void save(String title, String length, File upFile) throws Exception {
        String path="http://192.168.1.17:8080/Test1/news.do";
        Map<String,String> params=new HashMap<String,String>();
        params.put("title",title);
        params.put("timeLength",length);
        FormFile files=new FormFile(upFile,"files","image/pjpeg");
        SocketHttpRequester.post(path, params, new FormFile[]{files});
        
    }
/**
 * 手动组建POST请求上传文件
 */
public class SocketHttpRequester {

    public static boolean post(String path,Map<String,String> params,
            FormFile[] files) throws Exception{
        //数据分割线
        final String BOUNDARY="---------------------------8015418710398";
        //数据结束标志
        final String endLine="--"+BOUNDARY+"--\r\n";
        int fileDataLength=0;
        
        //得到文件类型数据总长度
        for(FormFile uploadFile:files){
            StringBuilder fileExplain=new StringBuilder();
            fileExplain.append("--");
            fileExplain.append(BOUNDARY);
            fileExplain.append("\r\n");
            fileExplain.append("Content-Disposition: form-data;");
            fileExplain.append(" name=\""+uploadFile.getParameterName()+"\";");
            fileExplain.append(" filename=\""+uploadFile.getFilename()+"\";\r\n");
            fileExplain.append("Content-Type: "+uploadFile.getContentType()+"\r\n\r\n");
            fileDataLength+=fileExplain.length();
            if(uploadFile.getInputStream()!=null){
                fileDataLength+=uploadFile.getFile().length();
            }else{
                fileDataLength+=uploadFile.getData().length;
            }
            fileDataLength+="\r\n".length();
        }
        
        //构造文本类型参数的实体数据
        StringBuilder textEntity=new StringBuilder();
        for(Map.Entry<String,String> entry:params.entrySet()){
            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");
        }
        
        //计算传输给服务端的实体数据长度
        int dataLength=textEntity.toString().getBytes().length
                +fileDataLength
                +endLine.getBytes().length;
        
        URL url=new URL(path);
        int port=url.getPort()==-1?80:url.getPort();
        Socket socket=new Socket(InetAddress.getByName(url.getHost()),port);
        OutputStream outStream=socket.getOutputStream();
        //下面完成HTTP请求头的发送
        String requestmethod="POST"+url.getPath()+" HTTP/1.1\r\n";
        outStream.write(requestmethod.getBytes());
        String accept="Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
        outStream.write(accept.getBytes());
        String language="Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3";
        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请求头后根据HTTP协议需要以回车符换行
        outStream.write("\r\n".getBytes());
        //发送所有的文本数据
        outStream.write(textEntity.toString().getBytes());
        //发送文件数据
        for(FormFile uploadFile:files){
            StringBuilder fileEntity=new StringBuilder();
            fileEntity.append("--");
            fileEntity.append(BOUNDARY);
            fileEntity.append("\r\n");
            fileEntity.append("Content-Disposition: form-data;");
            fileEntity.append(" name=\""+uploadFile.getParameterName()+"\";");
            fileEntity.append(" filename=\""+uploadFile.getFilename()+"\"\r\n");
            fileEntity.append("Content-Type: "+uploadFile.getContentType()+"\r\n\r\n");
            outStream.write(fileEntity.toString().getBytes());
            if(uploadFile.getInputStream()!=null){
                byte[] buffer=new byte[1024];
                int len=0;
                while((len=uploadFile.getInputStream().read(buffer, 0,1024))!=-1){
                    outStream.write(buffer, 0,len);
                }
                uploadFile.getInputStream().close();
            }else{
                outStream.write(uploadFile.getData(),0,uploadFile.getData().length);
            }
            outStream.write("\r\n".getBytes());
            //发送结束标志
            outStream.write(endLine.getBytes());
            
            BufferedReader reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
            if(reader.readLine().indexOf("200")==-1){
                //读取服务端返回的数据,判断请求吗是否为200
                return false;
            }
            outStream.flush();
            outStream.close();
            reader.close();
            socket.close();
            return true;
            
            
            
        }
        return false;
    }
}

4.MainActivity
public void save(View view){
        EditText titleText=(EditText)findViewById(R.id.title);
        EditText lengthText=(EditText)findViewById(R.id.timeLength);
        EditText fileText=(EditText)findViewById(R.id.fileName);
        String title=titleText.getText().toString();
        String length=lengthText.getText().toString();
        String fileName=fileText.getText().toString();
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)||
                Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)){
            File upFile=new File(Environment.getExternalStorageDirectory(),fileName);
            if(upFile.exists()){
                VideoNewsService service=new VideoNewsService();
                try {
                    service.save(title,length,upFile);
                    Toast.makeText(getApplicationContext(), "保持成功",2);
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "保持失败",2);
                }
            }else{
                Toast.makeText(getApplicationContext(),fileName+"文件不存在",2).show();
            }
        }
        else{
            VideoNewsService service=new VideoNewsService();
            try {
                service.save(title,length);
                Toast.makeText(getApplicationContext(), "保持成功",2);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), "保持失败",2);
            }
        }
        
    }


你可能感兴趣的:(Android_POST文件上传)