Android 手机上传图片至javaweb服务器(servlet)


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"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>myServer</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  
    <servlet>
    <servlet-name>UploadImage</servlet-name>
    <servlet-class>servlet.UploadImage</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>UploadImage</servlet-name>
    <url-pattern>/uploadImage</url-pattern>
  </servlet-mapping>
  
</web-app>





    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<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> 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

猜你喜欢

转载自blog.csdn.net/qq_28468727/article/details/53264748