对于类似的功能(将照片从 Android 加载到 servlet),这是我使用的 Android 客户端代码(稍作编辑以便在此处发布):
URI uri = URI.create(// path to file);
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
// several key-value pairs to describe the data, one should be filename
entity.addPart("key", new StringBody("value"));
File inputFile = new File(photoUri.getPath());
// optionally reduces the size of the photo (you can replace with FileInputStream)
InputStream photoInput = getSizedPhotoInputStream(photoUri);
entity.addPart("CONTENT", new InputStreamBody(photoInput, inputFile.getName()));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(uri);
HttpContext localContext = new BasicHttpContext();
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost, localContext);
这是接收它的代码。首先,确保将您的 servlet 类标记为支持多部分消息:
@MultipartConfig
public class PhotosServlet extends HttpServlet
然后是身体的相关部分:
HttpEntity entity = new InputStreamEntity(request.getPart("CONTENT").getInputStream(), contentLength);
InputStream inputFile = entity.getContent();
// string extension comes from one of the key-value pairs
String extension = request.getParameter(//filename key);
// first write file to a file
File images = new File(getServletContext().getRealPath("images"));
File filePath = File.createTempFile("user", extension, images);
writeInputDataToOutputFile(inputFile, filePath); // just copy input stream to output stream
String path = filePath.getPath();
logger.debug("Wrote new file, filename: " + path);
希望能帮助到你。