使用Jax-rs Restful Service上传Android图像

时间:2015-07-19 00:02:26

标签: android image upload android-async-http ion

我有jax-rs restful文件上传服务。

我的上传服务代码:

import java.io.File;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import static org.apache.commons.lang3.RandomStringUtils.randomAlphanumeric;


@Path("/file")
public class UploadFileService {

@Context
private ServletContext sc;

@POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("application/json;charset=UTF-8")
public String handleRegistration(@Context HttpServletRequest req) throws Exception {
    try {
      StringBuilder files = new StringBuilder();
    //String username = null;
    FileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setHeaderEncoding("ISO-8859-1");

    List items = upload.parseRequest(req);
    Iterator iter = items.iterator();

    String returnVal ="";

    while (iter.hasNext()) {
        FileItem item = (FileItem) iter.next();

        /* if (item.isFormField()) {
            if ("uname".equals(item.getFieldName())) {
                username = item.getString();
            }

        } else { */
            if (!item.isFormField()) {

                files.append(item.getName()).append(",");
                File fullFile = new File(item.getName());

                String ext = "";

                if (item.getContentType().contains("jpeg")) {
                    ext = ".jpeg";
                } else if (item.getContentType().contains("jpg")) {
                    ext = ".jpg";
                } else if (item.getContentType().contains("png")) {
                    ext = ".png";
                }
                else
                    return "";

                String fName = randomAlphanumeric(30);

                System.out.println(sc.getRealPath("/"));

                String myRealPath = sc.getRealPath("/").concat("images/");

                System.out.println(myRealPath);

                File savedFile = new File(myRealPath, fName.concat(ext));

                //File savedFile = new File("D:/uploaded/",     fName.concat(ext));
                item.write(savedFile);

                returnVal = fName.concat(ext); //myRealPath + fName.concat(ext)
            }
        }
    //}
    //return Response.status(200).entity("Hi " + username + " ! File syou uploaded are [" + files.toString() + "]").build();

    return "{\"filename\": \"" + returnVal   + "\"}";  
    } catch (Exception e) {
        return e.getMessage();
    }

 }
 }

我使用浏览器对示例代码进行了测试,但没有任何错误。

我的示例代码:

<h2>File Upload Example</h2>  
<form action="/our/file/upload" method="post" enctype="multipart/form-data">  
   <p>  
    Select a file : <input type="file" name="file" size="45" />  
   </p>  
   <input type="submit" value="Upload File" />  
</form> 

我正在尝试在Android上opload照片。我尝试了4-5库,但我无法从android上传图片。

对于使用AsyncHttpClient的代码:

 AsyncHttpClient client = new AsyncHttpClient();
    File myFile = new File(imagepath);
    RequestParams params = new RequestParams();
    try {
        params.put("profile_picture", myFile);
    } catch(FileNotFoundException e) {}



    client.post(getApplicationContext(), ServiceUrl, params, new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
            int l = 1;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
            int l = 1;
        }
    });

使用Ion Library代码:

 Ion.with(getApplicationContext())
            .load(ServiceUrl)

            .setMultipartParameter("goop", "noop")
            .setMultipartFile("filename.zip", new File(imagepath))
            .asJsonObject();

我没有得到任何错误,你有什么建议吗?为什么服务不能用于android?此致

0 个答案:

没有答案