我有一个基于python flask的后端web应用程序,它有这个方法来接受图像。@app.route('/getNoteText',methods=['GET','POST'])
def GetNoteText():
if request.method == 'POST':
file = request.files['pic']
filename = file.filename
file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
processImage(filename)
else:
return "Y U NO USE POST?"
我的android函数调用了这个方法/**
* Uploading the file to server
*/
private class UploadFileToServer extends AsyncTask {
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... params) {
return uploadFile();
}
private String uploadFile() {
String responseString = null;
Log.d("Log", "File path" + opFilePath);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(Config.FILE_UPLOAD_URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
@Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
ExifInterface newIntef = new ExifInterface(opFilePath);
newIntef.setAttribute(ExifInterface.TAG_ORIENTATION,String.valueOf(2));
File file = new File(opFilePath);
entity.addPart("pic", new FileBody(file));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
// Making server call
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(r_entity);
Log.d("Log", responseString);
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode + " -> " + response.getStatusLine().getReasonPhrase();
Log.d("Log", responseString);
}
} catch (ClientProtocolException e) {
responseString = e.toString();
} catch (IOException e) {
responseString = e.toString();
}
return responseString;
}
}
这是文件上传URL,它指的是我的python应用程序在上面创建的webservice。public static final String FILE_UPLOAD_URL = "http://:5000/getNoteText";
我们正在获取已被拍摄并存储在android文件系统中的图像,并使用如下UploadFileToServer类:String filePath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) +
File.separator + Config.IMAGE_DIRECTORY_NAME;
File dirFile = mkDir(filePath);
File outputFile = new File(dirFile, String.format("%d.png", System.currentTimeMillis()));
outStream = new FileOutputStream(outputFile);
outStream.write(data);
outStream.close();
opFilePath = outputFile.getAbsolutePath();
UploadFileToServer uploadFileToServer = new UploadFileToServer();
uploadFileToServer.execute();
您可以使用这个uploadFileToServer将任何类型的文件发送到后台。您不需要仅限于图像。
希望这有帮助!