我想使用Volley image
将server
上传到StringRequest
。早些时候我使用VolleyPlus SimpleMultipartRequest
做了它并且它工作正常。但是现在我改变了托管,并且由于某些编码,它不接受SimpleMultipartRequest
的数据所以现在我必须使用StringRequest
发送它,但它不会上传。或者我必须在php中添加一些内容,因为现在它正在获取字符串请求而不是多部分请求。
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
final Uri imageUri = Uri.parse(intent.getStringExtra("image"));
filepath = getPath(Upload.this, imageUri);
btnUpload.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
caption = txtCaption.getText().toString();
if (filepath != null){
progressDialog.show();
imageUpload(filepath);
}else {
Toast.makeText(Upload.this, "Image not Selected", Toast.LENGTH_SHORT).show();
}
}
});
}
private void imageUpload(final String imagePath){
StringRequest smr = new StringRequest(Request.Method.POST, IMAGE_UPLOAD_URL, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(Upload.this, "Image Uploaded", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
finish();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(com.android.volley.error.VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<>();
// the POST parameters:
params.put("uploadedfile", imagePath);
params.put("userid", userid);
params.put("caption", caption);
params.put("product","normal");
return params;
}
};
MyApplication.getInstance().addToRequestQueue(smr);
}
public String getPath(Context context, Uri contentUri) {
//copy file and send new file path
File TEMP_FILE = new File(Environment.getExternalStorageDirectory(),"/My Children");
TEMP_FILE.mkdir();
String fileName = getFileName(contentUri);
if (!TextUtils.isEmpty(fileName)) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyymmdd_hhmmss");
String timestamp = simpleDateFormat.format(new Date());
userid = SharedPreferenceManager.getmInstance(Upload.this).getMobileno();
File copyFile = new File( TEMP_FILE + userid +".jpg");
copy(context, contentUri, copyFile);
return copyFile.getAbsolutePath();
}
return null;
}
public static String getFileName(Uri uri) {
if (uri == null) return null;
String fileName = null;
String path = uri.getPath();
int cut = path.lastIndexOf('/');
if (cut != -1) {
fileName = path.substring(cut + 1);
}
return fileName;
}
public static void copy(Context context, Uri srcUri, File dstFile) {
try {
InputStream inputStream = context.getContentResolver().openInputStream(srcUri);
if (inputStream == null) return;
OutputStream outputStream = new FileOutputStream(dstFile);
org.apache.commons.io.IOUtils.copy(inputStream, outputStream);
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
MyApplication类
public class MyApplication extends Application {
public static final String TAG = MyApplication.class.getSimpleName();
private RequestQueue mRequestQueue;
private static MyApplication mInstance;
@Override
public void onCreate() {
super.onCreate();
mInstance = this;
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
getRequestQueue().add(req);
}
public <T> void addToRequestQueue(Request<T> req) {
req.setTag(TAG);
getRequestQueue().add(req);
}
public void cancelPendingRequests(Object tag) {
if (mRequestQueue != null) {
mRequestQueue.cancelAll(tag);
}
}
}
PHP脚本
<?php
$uploaddir = 'ImagesUpload/';
$userid=$_POST['userid'];
$caption=$_POST['caption'];
$category=$_POST['product'];
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error)
{
die("Connection failed: " . $conn->connect_error);
}
else
{
$sql = "SELECT ImgID FROM ImgInfo WHERE UserID ='$userid' ORDER BY ImgUploadDate DESC LIMIT 1";
$result = $conn->query($sql);
if ($result->num_rows > 0)
{
// output data of each row
while($row = $result->fetch_assoc())
{
$tempID=$row["ImgID"];
}
$nxtIndex=(int)(substr($tempID,strpos($tempID,"I")+1,strlen($tempID))+1);
$imgID=$userid."I".$nxtIndex;
}
else
{
$imgID=$userid."I1";
}
$_FILES["uploadedfile"]["name"]=$imgID.".jpg";
$uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
if (copy($_FILES['uploadedfile']['tmp_name'], $uploadfile))
{
$filename="ImagesUpload/".$_FILES["uploadedfile"]["name"];
$sql = "INSERT INTO ImgInfo (UserID,ImgCategory,ImgLink,ImgID,ImgUploadDate,ImgCaption) VALUES ('$userid','$category', '$filename','$imgID',CURRENT_TIMESTAMP,'$caption')";
if ($conn->query($sql) === TRUE)
{
if ($category=='Profile')
{
$resultreturn = array();
array_push($resultreturn,array('PPurl'=>'http://smilestechno.000webhostapp.com/'.$filename));
echo json_encode(array("result"=>$resultreturn),JSON_UNESCAPED_SLASHES);
}
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
}
else
{
echo "Upload failed";
}
}
?>