从xamarin表单上传图片到php服务器

ijnw1ujt  于 2023-04-18  发布在  PHP
关注(0)|答案(2)|浏览(129)

我一直在尝试从xamarin表单应用程序上传图片到php服务器,但似乎无法正常工作。服务器收到一个空的$_FILES请求。这是c#代码。

public async Task<bool> Upload(MediaFile mediaFile, string filename)
    {
        byte[] bitmapData;
        var stream = new MemoryStream();
        mediaFile.GetStream().CopyTo(stream);
        bitmapData = stream.ToArray();
        var fileContent = new ByteArrayContent(bitmapData);

        fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/octet-stream");
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
        {
            Name = "fileUpload",
            FileName = filename
        };

        string boundary = "---8393774hhy37373773";
        MultipartFormDataContent multipartContent = new MultipartFormDataContent(boundary);
        multipartContent.Add(fileContent);

        HttpClient httpClient = new HttpClient();
        HttpResponseMessage response = await httpClient.PostAsync("http://www.url.com/upload.php", multipartContent);
        response.EnsureSuccessStatusCode();

        if (response.IsSuccessStatusCode)
        {
            string content = await response.Content.ReadAsStringAsync();

            return true;
        }
        return false;
     }

下面是接收上传图片的php文件。我试图将发布的图片内容保存到文件中,但文件只有一个空数组,并且总是返回“失败”。请问我错过了什么错误?我已经搜索了网页,但似乎无法理解这个问题。

$uploads_dir = 'uploads/';
  $req_dump = print_r( $_FILES, true );
  $fp = file_put_contents( 'data.txt', $req_dump );
  if (isset($_FILES["fileUpload"]["tmp_name"]) AND is_uploaded_file($_FILES["fileUpload"]["tmp_name"])) 
  {
    $tmp_name = $_FILES["fileUpload"]["tmp_name"];
    $name = $_FILES["fileUpload"]["name"];
    $Result = move_uploaded_file($tmp_name, "$uploads_dir/$name");
    echo "Success";
  }
  else
  {
    echo "Failure";
  }
nwwlzxa7

nwwlzxa71#

我知道这是一个老职位,但这是我如何上传图像从Xamarin表单到PHP http://gjhdigital.com/xamarin/xamarin-forms-upload-image-to-php/
Xamarin C#代码

using Plugin.Media;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;
namespace UploadPicToServer
{
// Learn more about making custom code visible in the Xamarin.Forms previewer
// by visiting https://aka.ms/xamarinforms-previewer
[DesignTimeVisible(false)]
public partial class MainPage : ContentPage
{
public MainPage()
{
InitializeComponent();
}

private async void btnUpload_Clicked(object sender, EventArgs e)
{

if (!CrossMedia.Current.IsPickPhotoSupported)
{
await DisplayAlert("Photos Not Supported", ":( Permission not granted to photos.", "OK");
return;
}
var file = await Plugin.Media.CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions
{
PhotoSize = Plugin.Media.Abstractions.PhotoSize.Medium,

});

if (file == null)
return;

string fileName = file.Path;
image.Source = ImageSource.FromStream(() =>
{
var stream = file.GetStream();
file.Dispose();
return stream;
});

//UploadImage1(file.AlbumPath);
UploadImage(file.GetStream(), fileName);
}
private async void UploadImage(Stream mfile, string fileName)
{
int authorID = 2;
string username = "yourusername";

var url = "https://yourwebsite.com/ba-add-profile-pic.php";
url += "?author="+ authorID +"&username="+ username; //any parameters you want to send to the php page.

try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("https://yourwebsite.com/");
MultipartFormDataContent form = new MultipartFormDataContent();
//HttpContent content = new StringContent("fileToUpload");
//form.Add(content, "fileToUpload");

var stream = mfile;
StreamContent content = new StreamContent(stream);

//get file's ext
string fileExt = fileName.Substring(fileName.Length - 4);
string fName = "User-Name-Here-123" + fileExt.ToLower();

content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
{
Name = "fileToUpload",
FileName = fName
};
form.Add(content);
var response = await client.PostAsync(url, form);
var result = response.Content.ReadAsStringAsync().Result;

}
catch (Exception e)
{
//debug
Debug.WriteLine("Exception Caught: " + e.ToString());

return;
}
}

public static byte[] ToArray(Stream s)
{
if (s == null)
throw new ArgumentNullException(nameof(s));
if (!s.CanRead)
throw new ArgumentException("Stream cannot be read");

MemoryStream ms = s as MemoryStream;
if (ms != null)
return ms.ToArray();

long pos = s.CanSeek ? s.Position : 0L;
if (pos != 0L)
s.Seek(0, SeekOrigin.Begin);

byte[] result = new byte[s.Length];
s.Read(result, 0, result.Length);
if (s.CanSeek)
s.Seek(pos, SeekOrigin.Begin);
return result;
}
}
}

PHP代码

//parameters send in via querystring
if (!isset($_REQUEST['author']) || !isset($_REQUEST['username']) ) {
die('{"status" : "Bad", "reason" : "Invalid Access"}');
}

$userID = $_REQUEST['author'];
$isGood = false;
try{

$uploaddir = '../someFolderToStoreTheImage/';
$fileName = basename($_FILES['fileToUpload']['name']);
$uploadfile = $uploaddir . basename($_FILES['fileToUpload']['name']);

//CHECK IF ITS AN IMAGE OR NOT
$allowed_types = array ('image/jpeg', 'image/png', 'image/bmp', 'image/gif' );
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['fileToUpload']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
die ( '{"status" : "Bad", "reason" : "Not a valid image"}' );
}
//

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {
//echo "File is valid, and was successfully uploaded.\n";
echo '{"status" : "Success", "reason" "'. $fileName .'"}';
$isGood = true;
} else {
//echo "Possible file upload attack!\n";
echo '{"status" : "Bad", "reason" : "Unable to Upload Profile Image"}';
}

}
catch(Exception $e) {
echo '{"status" : "Bad", "reason" : "'.$e->getMessage().'"}';
}
yiytaume

yiytaume2#

AND运算符对你来说真的不是一个好的选择。(在第4行)。有时它会显示一些真正意想不到的行为。(我可以向你推荐'AND' vs '&&' as operator以获得更多信息)。
如果你想要一个逻辑AND,可以使用&&运算符。

if (isset($_FILES["fileUpload"]["tmp_name"]) && is_uploaded_file($_FILES["fileUpload"]["tmp_name"]))

相关问题