如何在我的 Web 服务器上传递我的 base64 字符串
本文关键字:我的 base64 字符串 服务器 Web | 更新日期: 2023-09-27 18:06:41
我的代码正确吗?我已经在我的 Web 服务器上发布了这个。发生的情况是,它正在创建一个文本文件,但 base64 字符串未写入该文本文件。
这些是我来自安卓工作室的代码
private void uploadImage() {
final ProgressDialog loading = ProgressDialog.show(this,"Uploading...","Please wait...",false,false);
StringRequest stringRequest = new StringRequest(Request.Method.POST, UPLOAD_URL,
new Response.Listener<String>() {
@Override
public void onResponse(String s) {
loading.dismiss();
Toast.makeText(MainActivity.this, s , Toast.LENGTH_LONG).show();
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError volleyError) {
loading.dismiss();
Toast.makeText(MainActivity.this, volleyError.getMessage().toString(), Toast.LENGTH_LONG).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
String image = getStringImage(bitmap);
Map<String,String> params = new Hashtable<String, String>();
params.put("b64", image);
Log.d("base64: ", String.valueOf(params));
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
这些是我在VS上的代码
[HttpPost]
public String ProcessImg([FromBody] string b64)
{
String base64 = b64;
String jsonStr = null;
//function to create image from b64 string
try
{
var FilePath = ConfigurationManager.AppSettings["imgFilePath"];
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
//to create file and write base64 string
var name = DateTime.Now.ToString("MMddyyyy-HHmmss");
var FileName = Path.Combine(FilePath, name + ".png");
string path = Path.Combine(FilePath, name + ".txt");
StreamWriter file = new StreamWriter(path);
file.Write(base64);
file.Close();
if (File.Exists(FileName))
{
jsonStr = "file successfully created on server. :" + FileName;
}
else
{
jsonStr = "Sorry the file you tried to convert failed.";
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
jsonStr = ex.Message;
}
//Algo
return jsonStr;
}
StreamWriter 最好与 using
关键字一起使用,因为它实现了自动调用 Dispose()
方法IDisposable
如下所示:
using(StreamWriter file = new StreamWriter())
{
file.Write(base64);
}
否则,您必须手动调用 Flush()
方法,以便在关闭文件之前将缓冲的输入写入磁盘:
StreamWriter file = new StreamWriter();
file.Write(base64);
file.Flush();
file.Close();
flush 部分是在调用流的 Dispose()
方法时完成的,因此使用 using
关键字实现它会自动解决这个问题。