Xutils上传图片(2)

来源:互联网 发布:nginx 自定义变量 编辑:程序博客网 时间:2024/05/29 17:47

1、
(1)、files

/*     * 创建一个以当前系统时间为名称的文件,防止重复----------(0)     */    private File tempFile = new File(Environment.getExternalStorageDirectory(),getPhotoFileName());    // 使用系统当前日期加以调整作为照片的名称    private String getPhotoFileName() {        Date date = new Date(System.currentTimeMillis());        SimpleDateFormat sdf = new SimpleDateFormat("'PNG'_yyyyMMdd_HHmmss");        return sdf.format(date) + ".png";    }

(2)、http发送请求:
//设置了相应时间为:10000
httpUtils=new HttpUtils(10000);

// 上传文件到服务器    protected void upload() {        RequestParams params=new RequestParams();        params.addBodyParameter(tempFile.getPath().replace("/", ""), tempFile);        httpUtils.send(HttpMethod.POST,URL, params,new RequestCallBack<String>() {            @Override            public void onFailure(HttpException e, String msg) {                Toast.makeText(MainActivity.this, "上传失败,检查一下服务器地址是否正确", Toast.LENGTH_SHORT).show();                Log.i("MainActivity", e.getExceptionCode() + "====="                        + msg);            }            @Override            public void onSuccess(ResponseInfo<String> responseInfo) {                Toast.makeText(MainActivity.this, "上传成功,马上去服务器看看吧!", Toast.LENGTH_SHORT).show();                Log.i("MainActivity", "====upload_error====="                        + responseInfo.result);            }        });    }

(3)、服务器接受文件流(smartupload接受)

public class UploadServlet extends HttpServlet {    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        doPost(request, response);    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        response.setContentType("text/html;charset=utf-8");        PrintWriter out = response.getWriter();        SmartUpload smartUpload = new SmartUpload();        String msg=request.getParameter("msg");        //out.print(msg);          try {              smartUpload.initialize(this.getServletConfig(), request, response);             smartUpload.upload();              com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);              if (!smartFile.isMissing()) {                  String saveFileName = "images/" + smartFile.getFileName();                  smartFile.saveAs(saveFileName, smartUpload.SAVE_VIRTUAL);                  out.print("ok:" + saveFileName+ ", msg:" + smartUpload.getRequest().getParameter("msg"));            } else {                  out.print("missing...");              }          } catch (Exception e) {              out.print(e+","+msg);          }         out.flush();        out.close();    }}
0 0
原创粉丝点击