Я использую asynktask с MultipartEntity для загрузки файлов, и я получил успешное сообщение MSG со стороны сервера, но мое изображение не загружается на сервер, даже если я получаю успешный ответ на любую помощь, я искал в Интернете, я не мог получить никакого соответствующего ответа на это мой код:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resume_upload_activity);
ivAttachment = (ImageView) findViewById(R.id.ivAttachment);
bUpload = (Button) findViewById(R.id.b_upload);
tvFileName = (TextView) findViewById(R.id.tv_file_name);
ivAttachment.setOnClickListener(this);
bUpload.setOnClickListener(this);
}
@Override
public void onClick(View v) {
if (v== ivAttachment){
//on attachment icon click
showFileChooser();
}
if (v== bUpload){
//on upload button Click
if (selectedFilePath != null){
new UploadImageTask().execute();
}else
{
Toast.makeText(getApplicationContext(),"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
}
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("image/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK){
if (requestCode == PICK_FILE_REQUEST){
if (data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
try {
selectedFilePath = FilePath.getPath(this,selectedFileUri);
} catch (Exception e) {
e.printStackTrace();
}
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if (selectedFilePath != null && !selectedFilePath.equals("")){
tvFileName.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
private class UploadImageTask extends AsyncTask<Void, Void, String> {
private ProgressDialog dialog = new ProgressDialog(FileUpload.this);
ByteArrayBody bab;
String response;
@Override
protected void onPreExecute()
{
dialog.setTitle("Uploading Image");
dialog.setMessage("Processing...");
dialog.setCancelable(true);
dialog.show();
}
@Override
protected String doInBackground(Void... params) {
try {
URL url = new URL(SERVER_URL);
Log.d(TAG,"Url Open");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//connection.connect();
String reqHead = "application/x-www-form-urlencoded";
connection.setRequestMethod("POST");
connection.setRequestProperty("connection","Keep-Alive"+reqHead);
//Header header = new Header();
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
File file= new File(selectedFilePath);
//file.toString(Bitmap.CompressFormat.JPEG,100,baos);
FileBody fileBody= new FileBody(file);
byte[] data = baos.toByteArray();
bab = new ByteArrayBody(data, "image");
entity.addPart("image",fileBody);
entity.addPart("Some other String to send",new StringBody("something"));
connection.addRequestProperty("content-length",entity.getContentLength()+"");
connection.addRequestProperty(entity.getContentType().getName(),entity.getContentType().getValue());
OutputStream os = connection.getOutputStream();
entity.writeTo(connection.getOutputStream());
os.close();
connection.connect();
if (connection.getResponseCode()==HttpURLConnection.HTTP_OK){
return readStream(connection.getInputStream());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private String readStream(InputStream inputStream) {
BufferedReader reader;
StringBuilder builder = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
try {
while ((line = reader.readLine())!=null){
builder.append(line);
}
response = builder.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return response;
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (response.equals("success")) {
dialog.dismiss();
Toast.makeText(getApplicationContext(), "Files Uploaded..", Toast.LENGTH_SHORT).show();
} else
Toast.makeText(getApplicationContext(), "Server Failed...", Toast.LENGTH_SHORT).show();
}
}
Любой мой URL-адрес некоторые думают, что URL-адрес правильный?
http://somurl.com/live?header = {"cameraId":"A_IVIS5045C1","encoderType":0}
Размер тела файла @srinu - это просто изображение, если я использовал этот URL-адрес, используя почтовый человек, я получил изображение, но если я использовал этот URL-адрес с Android, изображение не было загружено
вы отправляете URL-адрес изображения, как пару ключ-значение в почтальоне?
@srinu, я просто использую двоичный файл и загружаю файл.
обратитесь к этому vikaskanani.wordpress.com/2011/01/29/…
это не открытый хасан




Если вы используете MultipartEntity, я предлагаю вам свою библиотеку, которую я создал для загрузки файла (с данными или без).
Вот Git URL
Добавьте эту зависимость в свой модуль build.gradle:
dependencies {
compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'
}
добавьте свой файл в Hashmap:
HashMap<String, File> fileParameters = new HashMap<>();
fileParameters.put("fileKey", new File(filePath));
И выполнить запуск выполнения
new HttpRequestResponse(MainActivity.this)
.setOnResultListener(new HttpRequestResponse.ResultListener() {
@Override
public void onPostExecute(JSONObject json, String requestCode) {
Log.d(TAG, "json= = "+json.toString());
}
})
.setUrl("http://requestb.in/11xjkya1")
.setHeaderParameters(headerParameters) // Optional
.setStringParameters(stringParameters)
.setFileParameters(fileParameters)
.setMethod(HttpRequestResponse.Method.POST)
.isDialogShown(true, "Loading...")
.setSocketTimeOut(30)
.executeMethod();
Примечание: Это асинхронная задача.
спасибо, но я хочу загрузить файл с помощью составного запроса
Да, это мультичасть. Эта библиотека использует библиотеку http-mime для многопользовательской загрузки.
проверьте размер файла на вашей стороне, если он действителен, попросите парня на стороне сервера исправить проблему