Android Multipart上传 - 服务器端的getPart()返回null

时间:2014-05-27 07:30:31

标签: java android server-side multipart image-upload

我试图将图片从Android应用上传到我的服务器。发送' httpPost'似乎工作得很好,在服务器端代码,我在执行HTTPServletRequest.getPart(" filepart")时得到null。

Android活动代码

    public class ImageUpload extends Activity {

private static int RESULT_LOAD_IMAGE = 1;
Bitmap bm;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image_upload);

    Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK
            && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) findViewById(R.id.imgView);
        bm = BitmapFactory.decodeFile(picturePath);
        imageView.setImageBitmap(bm);

        SendHttpRequestTask t = new SendHttpRequestTask();
        t.execute();
    }
}

public void executeMultipartPost() {

}

private class SendHttpRequestTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            bm.compress(CompressFormat.JPEG, 75, bos);
            byte[] data = bos.toByteArray();
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost postRequest = new HttpPost(
                "http://192.168.43.85:8080/Albums/ImageUpload");
            ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("userfile", bab);
            postRequest.setEntity(reqEntity);
            httpClient.execute(postRequest);

        } catch (Exception e) {
            // handle exception here
            Log.e(e.getClass().getName(), e.getMessage());
        }
        return null;
    }

}

}

我的服务器端代码

@WebServlet("/ImageUpload")
@MultipartConfig
public class ImageUpload extends HttpServlet {
private static final long serialVersionUID = 1L;

/**
 * @see HttpServlet#HttpServlet()
 */
public ImageUpload() {
    super();
    // TODO Auto-generated constructor stub
}

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub
}

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     try {
            List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
            for (FileItem item : items) {
                if (item.isFormField()) {
                    // Process regular form field (input type="text|radio|checkbox|etc", select, etc).
                    String fieldname = item.getFieldName();
                    String fieldvalue = item.getString();
                    // ... (do your job here)
                } else {
                    // Process form file field (input type="file").
                    String fieldname = item.getFieldName();
                    InputStream filecontent =  request.getPart("userfile").getInputStream();
                    OutputStream out = new FileOutputStream("C:\\test.jpg" );
                    IOUtils.copy(filecontent, out); // The function is below
                    out.flush();
                    out.close();
                    request.getRequestDispatcher("index.jsp").forward(request, response);
                }
            }
        } catch (FileUploadException e) {
            throw new ServletException("Cannot parse multipart request.", e);
        }
}

}

执行此操作时,我在服务器端的getPart()方法上获得了NullPointerException。感谢对此的任何帮助/建议。

0 个答案:

没有答案