C#picturebox控件圖片以json格式上傳java後臺保存

關於winform上傳圖片到Java後端,保存到數據庫,有多種方法,本文主要介紹利用picturebox控件,點擊按鈕上傳圖片,將圖片轉化爲base64格式,以json格式上傳到Java後臺,再從java端解析,保存到數據庫。java

上代碼:
首先,畫面上添加一個picturebox控件,再添加一個button,給button設置click事件-獲取到base64格式的字符串。
數據庫

/// <summary>
/// 圖片上傳
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnUploadImage_Click(object sender, EventArgs e)
{
   OpenFileDialog openFileDialog = new OpenFileDialog();
   if (openFileDialog.ShowDialog() == DialogResult.OK)
   {
       //PictureBox控件顯示圖片
       picExpPic.Load(openFileDialog.FileName);
       //獲取用戶選擇文件的後綴名
       string extension = Path.GetExtension(openFileDialog.FileName);
       //聲明容許的後綴名
       string[] str = new string[] { ".gif", ".jpeg", ".jpg", ".png", ".bmp" };
       if (!str.Contains(extension))
       {
           MessageBox.Show("僅能上傳gif,jpge,jpg,png,bmp格式的圖片!");
       }
       else
       {
           Image img = this.picExpPic.Image;
           MemoryStream ms = new MemoryStream();
           img.Save(ms, img.RawFormat);
           byte[] bytes = ms.ToArray();
           ms.Close();
           string strbaser64 = Convert.ToBase64String(bytes);
           imgStr = "data:image/jpg;base64," + strbaser64;
       }
   }
}

把字符串imgStr拼接成json格式,上傳。c#連接Java後臺代碼,後續給出。
java後臺接收json:json

/**
 * 新增信息
 * @return
 */
@RequestMapping(value="/addInfo")
@ResponseBody
public Result addInfo(String strJson,HttpServletRequest request){
  JSONObject object = new JSONObject(strJson);
  String base64 = object.getString("Expertpic");
  //轉爲file格式---獲取圖片信息
  MultipartFile fileExpPic = base64ToMultipart(base64);             
  Result result = new Result();
  int ret = 0;
  //格式化字符串
    String base = base64.replace(" ", "+");
  //去掉頭部
      String[] baseStrs = base.split(",");
      BASE64Decoder decoder = new sun.misc.BASE64Decoder();
      byte[] bytes1;
      String filePath2 = null;
      String fileName2 = null;
  try {         
    filePath2 = request.getServletContext().getRealPath("resources\\\\uploads")+"\\";
    fileName2 = "expertpic"+sdf.format(dt)+"."+(fileExpPic).getOriginalFilename().substring((fileExpPic).getOriginalFilename().lastIndexOf(".")+1);
    //轉化爲文件流
    bytes1 = decoder.decodeBuffer(baseStrs[1]);
        //生成jpeg圖片
        String imgFilePath = filePath2+fileName2;//新生成的圖片
        OutputStream out = new FileOutputStream(imgFilePath);   
        out.write(bytes1);
        out.flush();
        out.close();
  } catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
  }
  File dir = new File(filePath2);
  if(!dir.exists()) {
    dir.mkdirs();
  }
  try {                  
    A a=new A();
    a.temp="";
    ret =this.addService.addInfo(a);
    if(ret==0) {
      result.setSuccess(false);
      result.setErrMsg("失敗!");
    }else {
      result.setSuccess(true);
    }
  } catch (Exception e) {
    result.setSuccess(false);
    result.setErrMsg("失敗!");
  }
  return result;
}

java base64轉化爲File方法:c#

public static MultipartFile base64ToMultipart(String base64) {
    try {
        String base = base64.replace(" ", "+");
        String[] baseStrs = base.split(",");
        BASE64Decoder decoder = new sun.misc.BASE64Decoder();
        byte[] bytes1 = decoder.decodeBuffer(baseStrs[1]);
        return new BASE64DecodedMultipartFile(bytes1, baseStrs[0]);
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

保存到數據的是本身拼的圖片名稱和圖片後綴,圖片的存儲位置在本身指定的項目目錄。
至此c#上傳圖片告一段落後端

相關文章
相關標籤/搜索