Android使用xutils图片上传和服务器接收

使用xUtils   https://github.com/wyouflf/xUtils上传图片:


Client:

需要Xutils.jar

调用上传:

	String uploadHost="http://129.44.0.137:8080/AndroidUploadServer/upload.do";
	RequestParams params=new RequestParams();
	params.addBodyParameter("msg",imgtxt.getText().toString()); 
	params.addBodyParameter(filePath.replace("/", ""), new File(filePath));	
	uploadMethod(params,uploadHost);


上传方法:

	public  void uploadMethod(final RequestParams params,final String uploadHost) {
		http.send(HttpRequest.HttpMethod.POST, uploadHost, params,new RequestCallBack<String>() {
					@Override
					public void onStart() {
//						msgTextview.setText("conn...");
					}
					@Override
					public void onLoading(long total, long current,boolean isUploading) {
						if (isUploading) {
//							msgTextview.setText("upload: " + current + "/"+ total);
						} else {
//							msgTextview.setText("reply: " + current + "/"+ total);
						}
					}
					@Override
					public void onSuccess(ResponseInfo<String> responseInfo) {
//						msgTextview.setText("reply: " + responseInfo.result);
					}
					@Override
					public void onFailure(HttpException error, String msg) {
//						msgTextview.setText(error.getExceptionCode() + ":" + msg); 
					}
				});
	}



Server:

需要smartupload.jar猛戳下载      测试代码下载

import com.jspsmart.upload.SmartUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UploadServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("text/html,charset=UTF-8");

        SmartUpload smartUpload = new SmartUpload();

        try {
            smartUpload.initialize(this.getServletConfig(), request, response);
            smartUpload.upload();
            com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);
            if (!smartFile.isMissing()) {
                String saveFileName = "/data/" + smartFile.getFileName();
                smartFile.saveAs(saveFileName, smartUpload.SAVE_PHYSICAL);
                response.getWriter().print("ok:" + saveFileName + ", msg:" + smartUpload.getRequest().getParameter("msg"));
            } else {
                response.getWriter().print("missing...");
            }
        } catch (Exception e) {
            response.getWriter().print(e);
        }

    }

}


-------------------------------------------------------------------以下代码是早期写的测试代码,仅做参考-----------------------------------------------------------------------------------------


界面很简单,点击 【选择图片】,从图库里选择图片,显示到下面的imageview里,点击上传,就会上传到指定的服务器

Android使用xutils图片上传和服务器接收_第1张图片



你可能感兴趣的:(图片上传)