1

我有 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 上加载照片。我尝试了 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.with(getApplicationContext())
            .load(ServiceUrl)

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

我没有收到任何错误,您能给我任何建议吗?为什么该服务不适用于android?问候

4

0 回答 0