javaWeb服务器中doPost的代码

需要导入jspsmartupload.jar包,导入jspsmartupload.jar需要将其放在WebContent/WEB_INF/lib目录下,放在该目录下之后刷新右键该包选择Build Path -> Add to Buid Path。

SmartUpload的一些用法如下,具体的用法参考:http://www.voidcn.com/blog/u011990285/article/p-3423327.html

/** * SmartUpload 的用法 *///初始化SmartUpload mySmartUpload = new SmartUpload();mySmartUpload.initialize(getServletConfig(),request,response);//设置每个上传文件的最大长度(可选)mySmartUpload.setMaxFileSize(1024*1024);//限制总上传数据的长度(可选)mySmartUpload.setTotalMaxFileSize(1024*1024*10);//允许上传的文件(通过扩展名限制),仅允许上传doc,txt文件mySmartUpload.setAllowedFilesList("doc,txt");//设置禁止上传的文件(通过扩展名限制),禁止ext,bat(可选)try {mySmartUpload.setDeniedFilesList("ext,bat");} catch (SQLException e) {e.printStackTrace();}//准备上传try {mySmartUpload.upload();} catch (SmartUploadException e) {//向客户端返回错误信息response.getWriter().print(e);}//读取除了文件之外的数据Request  otherRequest  = mySmartUpload.getRequest();//如果在客户端中传输了中文,有可能会出现中文乱码,因此会使用了URL编码,那么我们就需要对接收的参数进行URL解码,否则就不需要String userName = URLDecoder.decode(otherRequest.getParameter("userName"),"UTF-8");String userId = otherRequest.getParameter("userId");String savePath = "c://";//保存文件for (int i = 0; i < mySmartUpload.getFiles().getCount(); i++) {//读取文件 com.jspsmart.upload.File file = mySmartUpload.getFiles().getFile(i); if (file.isMissing()) continue; try {file.saveAs(savePath + file.getFileName());} catch (SmartUploadException e) {//向客户端返回错误信息response.getWriter().println(e);}}


web服务器以及配置

UploadImage.servlet

/** * Servlet implementation class UploadImage */@WebServlet("/UploadImage")public class UploadImage extends HttpServlet {private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public UploadImage() {        super();        // TODO Auto-generated constructor stub    }/** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html,charset=UTF-8");  //保存在本地的路径String saveFilePath = "C://";//保存在本地的文件名String fileName;        try {          SmartUpload smartUpload = new SmartUpload();            smartUpload.initialize(this.getServletConfig(), request, response);          smartUpload.upload();                //获取其他的数据        Request otherReq = smartUpload.getRequest();        //获取从客户端传输过来的用户名,在客户端中对参数进行参数URL编码了,所以服务器这里要进行URL解码         String userName= URLDecoder.decode(otherReq.getParameter("userName"),"utf-8");        //获取从客户端传输过来的用户ID        String userId = otherReq.getParameter("userId");                //获取上传的文件,因为知道在客户端一次就上传一个文件,所以我们就直接取第一个文件            com.jspsmart.upload.File smartFile = smartUpload.getFiles().getFile(0);              //判断文件是否丢失            if (!smartFile.isMissing()) {              //获得文件名            fileName = smartFile.getFileName();            saveFilePath += fileName;               //另保存至本地                smartFile.saveAs(saveFilePath, smartUpload.SAVE_PHYSICAL);                                //给客户端返回确认信息                String responseStr = "ok:" + saveFilePath + ",userName:"+userName +", userId:" + userId;                OutputStream out = response.getOutputStream();                out.write(responseStr.getBytes("UTF-8"));                out.close();                System.out.println(userName);            } else {                response.getWriter().print("missing...");              }          } catch (Exception e) {            response.getWriter().print(e+".........");        }          }

web.xml

<?xml version="1.0" encoding="UTF-8"?>  myServer      index.html    index.htm    index.jsp    default.html    default.htm    default.jsp              UploadImage    servlet.UploadImage        UploadImage    /uploadImage    





    private void myupload(String path,String url) {        RequestParams params = new RequestParams();        params.addBodyParameter("userId", "1301010001");        try {            //对中文参数进行URL编码,然后在服务器那边对参数进行URL解码            params.addBodyParameter("userName", URLEncoder.encode("张三", "utf-8"));        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }//      传图片时,要写3个参数//      imageFile:键名//      new File(path):要上传的图片,path图片路径//      image/jpg:上传图片的扩展名        params.addBodyParameter("imageFile", new File(path), "image/jpg");        HttpUtils http = new HttpUtils();        http.configResponseTextCharset("utf-8");        http.send(HttpMethod.POST,                url,                params, new RequestCallBack() {                    @Override                    public void onSuccess(ResponseInfo responseInfo) {                        String resultStr = responseInfo.result;                        Log.e("1", "上传成功:" + resultStr);                    }                    @Override                    public void onFailure(HttpException error, String msg) {                        Log.e("1", "上传失败:" + error.getExceptionCode() + ":" + msg);                    }                });    }


xUtil jar包

jarsmartupload

更多相关文章

  1. Android2.2快速入门 zz
  2. Androidstudio打包jar和arr包
  3. AndroidStudio 升级后遇到的问题
  4. Android中Listview通过适配器设置Item的高度及其他样式
  5. Android(安卓)Debug Tools
  6. Android工程中配置OpenCV
  7. Android(安卓)中Odex文件生成与合并
  8. Binder机制原理学习笔记(4)_ServiceManager启动Binder分析
  9. Android升级到2.3之后遇到的问题

随机推荐

  1. Activiy或者Fragment 销毁时,Dialog 的正
  2. UI控件--自定义SeekBar样式
  3. Android之apk文件签名——keytool 和 jar
  4. 开发规范真的很重要
  5. No instrumentation runner found for th
  6. 【Android】利用Strings资源文件来格式化
  7. Android(安卓)sd存储总结
  8. 【Tech-Android-View】Android4.0的横竖
  9. Android(安卓)搭建MVP+Retrofit+RxJava网
  10. Android获取目录