使用xUtils https://github.com/wyouflf/xUtils上传图片:
Client:
需要Xutils.jar
调用上传:
String uploadHost=":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>() {@Overridepublic void onStart() {//msgTextview.setText("conn…");}@Overridepublic void onLoading(long total, long current,boolean isUploading) {if (isUploading) {//msgTextview.setText("upload: " + current + "/"+ total);} else {//msgTextview.setText("reply: " + current + "/"+ total);}}@Overridepublic void onSuccess(ResponseInfo<String> responseInfo) {//msgTextview.setText("reply: " + responseInfo.result);}@Overridepublic 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里,点击上传,就会上传到指定的服务器
版权声明:本文为博主原创文章,未经博主允许不得转载。
有时不但是必要的,而且是很有必要的。