This is not a duplicate of How to call Imgur API.

I tried to upload to imgur using its API, but (as my friends test) the API of imgur cannot be called in Chinese mainland. Then I found that halirutan has a technology to upload an image to imgur even without any account information via http://stackoverflow.com/upload/image. Now I can upload image to imgur by his function SEUploader`sendImage. Little pity is that he implemented it with Java code.

We can find his code here. I get nothing after researching his Java code. Can we do the same thing in pure Mathematica using new functions introduced in version 11.0 such as HTTPRequest, URLRead and so on?


1 Answer 1


Update on June 29th, 2020

Since API has changed, the new code is here:

getFKey[] := 
   "fkey: '" ~~ Shortest[fkey___] ~~ "'" :> fkey]
uploadImageSE[imagePath_] := 
  req = HTTPRequest[
https=true", <|Method -> "POST", 
     "Body" -> {"file" -> File[imagePath], "fkey" -> getFKey[]}|>];
  ImportString[URLRead[req]["Body"], "RawJSON"]["UploadedImage"]]

This is expected to work with jpg and png files. You need to input the path to image, just like an upload.

uploadImageSE[imagePath_] := 
  req = HTTPRequest[
    "http://stackoverflow.com/upload/image", <|
     "Body" -> {"image" -> <|"Content" -> File[imagePath], 
         "MIMEType" -> "image/png"|>}
  StringCases[URLRead[req, "Body"], "http" ~~ __ ~~ ".jpg" | ".png"] //


Remember to remove the double quotes before accessing.

  • $\begingroup$ That java code mislead me.Orz... $\endgroup$
    – yode
    Apr 5, 2017 at 3:38
  • $\begingroup$ If you've already set "MIMEType" -> "image/png", then you don't need to search for ".jpg". You can do something like First[StringCases[URLRead[req, "Body"], RegularExpression["closeDialog\\(\"(.+)\"\\)"] -> "$1"]]. $\endgroup$ Apr 5, 2017 at 4:35
  • $\begingroup$ @J.M. even if I set it to be png, I found the uploaded file to be .jpg sometimes when the original file is .jpg $\endgroup$
    – vapor
    Apr 5, 2017 at 5:35
  • $\begingroup$ Ah. In that case, the StringCases[] code I gave should work no matter what the file extension is. $\endgroup$ Apr 5, 2017 at 6:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.