Efficient way to upload an image to PHP from Android - javascript

I am uploading an image to PHP from Android by converting it to the byte array. After that I simply submit it using POST method.
On server side I do the reverse of what I am doing at client (Android app) side.
I was wondering if there is any other good/efficient/smart way to do this.
Note: I only have to use only PHP/JS/HTML and obviously Java at client side.

One of the most efficient ways is doing it using Volley, so make sure to include it in your gradle:
compile 'com.android.volley:volley:1.0.0'
I personally use Universal Image Loader which is included automatically when you include Volley. Since you haven't put any code that you tried, i'll give you some examples. In your activity that you're trying to upload the image, create a button. Add this code when that button is clicked:
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
i.setType("image/*");
startActivityForResult(i, Constants.VALUE_BROWSE_IMAGE_REQUEST);
This will open the gallery in your phone to browse for an image. Declare a variable at the top of your activity:
private Bitmap mBitmap;
After you choose the image you want to upload from your gallery, write this code:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Constants.VALUE_BROWSE_IMAGE_REQUEST &&
resultCode == RESULT_OK &&
data != null) {
try {
// Get the photo URI data
Uri filePath = data.getData();
// Get the Bitmap from Gallery
mBitmap = decodeBitmap(filePath, this);
} catch (IOException e) {
Toast.makeText(this, "Could not open picture.", Toast.LENGTH_SHORT).show();
}
}
}
Now that you have the bitmap of the chosen image, you need to convert that bitmap into base64 string so that Volley can be able to upload it:
// Before uploading the selected image to the server, we need to convert the Bitmap to String.
// This method will convert Bitmap to base64 String.
private String getStringImage(Bitmap bmp) {
ByteArrayOutputStream b = new ByteArrayOutputStream();
// This part handles the image compression. Keep the image quality
// at 70-90 so you don't cause lag when loading it on android
// (0-low quality but fast load, 100-best (original) quality but slow load)
bmp.compress(Bitmap.CompressFormat.JPEG, 80, b);
byte[] imageBytes = b.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
}
Finally you can start uploading the image:
private void uploadImage() {
StringRequest stringRequest = new StringRequest(
Request.Method.POST,
"URL_TO_YOUR_WEB_API",
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Failed to upload image.", Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
// Converting Bitmap to String
String image = getStringImage(mBitmap);
// Create parameters
Map<String, String> params = new Hashtable<>();
// Add parameters
params.put("action", "YOUR_BACKEND_KEY1");
params.put("...", image);
// Returning parameters
return params;
}
};
// Creating a Request Queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
// Adding request to the queue
requestQueue.add(stringRequest);
}
Make sure to replace the parameter strings with however you have created your backend in php.
Example URL:
http://yoursite.com/api.php?action=uploadimage&imagebase=adwtgiuewohnjsoiu&caption=somecaptiontext
Then the parameters in android would be:
params.put("action", "uploadimage");
params.put("imagebase", image);
params.put("caption", "somecaptiontext");

Related

HTML5 File upload using .NET Core 2.0 Web api

This question might be a duplicate, in that case I would love to get a reading on it, but please check if the duplicate question fits mine. I have tried looking for answers, but have not found any that fits my question correctly.
I have a website built with React served from a .NET Core 2.0 project with a regular Web API generated from the regular Controller web api that is built in to the project. The Web API is set up like this:
[Produces("application/json")]
[Route("api/File")]
public class FileController : Controller
{
// POST: api/File
[HttpPost]
public ActionResult Post()
{
Console.WriteLine(Request);
return null;
}
I want to upload Images / PDF files and other file types from a regular input type="file" field.
The code for that can be seen below:
export class Home extends Component {
render() {
return <input type = "file"
onChange = {
this.handleFileUpload
}
/>
}
handleFileUpload = (event) => {
var file = event.target.files[0];
var xhr = new XMLHttpRequest();
var fd = new FormData();
xhr.open("POST", 'api/File', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status == 200) {
// Every thing ok, file uploaded
console.log(xhr.responseText); // handle response.
}
};
fd.append("upload_file", file);
xhr.send(fd);
}
}
What needs to be implemented in the Post-file-controller part for the correct handling of the file? If I want the file to be uploaded as, say a uint8 array (to be stored).
Every bit of help is appreciated as I am stuck.
I'm a bit late to the party but if anybody else struggles with this problem: The reason the backend parameter file was null in my case, was because the input name in the frontend must be the same as the method parameter name in the backend.
In your example you chose the input name upload_file
fd.append("upload_file", file);
so the parameter in the backend must have the same name:
[HttpPost]
public void PostFile(IFormFile upload_file)
{
_fileService.Add(upload_file);
}
I will assume you meant byte[] by saying uint8 array. You can try using the new IFormFile interface.
[Route("api/File")]
public class FileController : Controller
{
// POST: api/file
[HttpPost]
public ActionResult Post(IFormFile file)
{
var uploadPath = Path.Combine(_hostingEnvironment.WebRootPath, "uploads");
if (file.Length > 0) {
var filePath = Path.Combine(uploads, file.FileName);
using (var fileStream = new FileStream(filePath, FileMode.Create)) {
//You can do anything with the stream e.g convert it to byte[]
byte[] fileBytes = new byte[fileStream.Length];
//Read the stream and write bytes to fileBytes
fileStream.Read(fileBytes, 0, fileBytes.Length);
//fileBytes will contain the file byte[] at this point
//Persist the file to disk
await file.CopyToAsync(fileStream);
}
}
//....
}
Edit: Make sure the parameter name IFormFile file* matches the name you are sending from the client, in your case it should be IFormFile upload_file

Java: Image upload with JavaScript - File is damaged, corrupted or too large

I am using Spring Boot as backend server and I have a JavaScript frontend.
For sending data between front- and backend I'm using the Axios library, which usually works pretty fine.
The Problem:
The image looks like this in the (Chrome) browser console:
It's a very very long alphanumeric string and that's what I send to the server with the following code:
static uploadFiles(files) {
const data = new FormData();
Object.keys(files).forEach(key => {
data.append("files", new Blob([files[key]], { type: 'image/jpeg' }));
});
const url = API_URL + "uploadFiles";
return axios.post(url, data, RestServices.getAuth({
"Content-Type": "multipart/form-data;boundary=gc0p4Jq0M2Yt08jU534c0p"
}));
}
I have no idea what the boundary thing does but it worked to receive a file in the backend tho...
On backend (spring) side I successfully receive an array of MultipartFiles:
#RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
#ResponseBody
public boolean uploadFiles(HttpServletRequest request, #RequestParam("files") MultipartFile[] files) throws IOException {
String filePath = Thread.currentThread().getContextClassLoader().getResource("assets/images/").getFile();
InputStream inputStream;
OutputStream outputStream;
for(MultipartFile file : files) {
File newFile = new File(filePath + file.getOriginalFilename() + ".jpg");
inputStream = file.getInputStream();
if (!newFile.exists() && newFile.createNewFile()) {
outputStream = new FileOutputStream(newFile);
int read;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
System.out.println(newFile.getAbsolutePath());
}
return true;
}
I've also tried it file.transferTo(newFile); instead of in- and outputstreams - which didn't work either.
After that I get the following output, which means that the image was saved successfully:
/path/to/blob.jpg
If I check the path where the file was uploaded, there is a file named blob.jpg, but if I open it, the windows photo viewer has the following problem:
I've opened the image before and after upload with notepad++:
Before upload:
I think this is a byte array, but If I open the image after upload I get exactly the output of the browser. This means it didn't get converted to a byte array (correct me if I'm wrong) and I believe that's why it's a corrupt image...
My questions are:
What's the problem?
How can I fix it?
I really tried everything which crossed my mind but I ran out of ideas.
Thanks for your help! :-)
I've read following *related* questions (but they **don't** have an answer):
[Question1][5], [Question2][6], and **many** more...
I've finally found an answer on my own!
I think the problem was that I used the e.target.result (which is used to show the image on the frontend) but insted I had to use the JS File object. The standard HTML 5 file input fields return those File objects (as I've read here).
The only thing I had to do now is to make a FormData object, append the File Object, set the FormData as Body and set the Content-Type header and that's it!
const data = new FormData();
data.append("files", fileObject);
return axios.post(url, data, {
"Content-Type": "multipart/form-data"
});
Those JS File Objects are recognized from Java as Multipart files:
#RequestMapping(value = "/uploadFiles", method = RequestMethod.POST)
#ResponseBody
public boolean uploadFiles(HttpServletRequest request, #RequestParam("files") MultipartFile[] files) {
boolean transferSuccessful = true;
for (MultipartFile file : files) {
String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf('.'));
String newFileName = genRandomName() + extension; //set unique name when saving on server
File newFile;
File imageFolder = new File(imageBasePath);
//check if parent folders exist else create it
if(imageFolder .exists() || imageFolder .mkdirs()) {
while ((newFile = new File(imageFolder .getAbsolutePath() + "\\" + newFileName)).exists()) {
newFileName = genRandomName(); //generate new name if file already exists
}
try {
file.transferTo(newFile);
} catch (IOException e) {
e.printStackTrace();
transferSuccessful = false;
}
} else {
LOG.error("Could not create folder at " + imageFolder.getAbsolutePath());
transferSuccessful = false;
}
}
return transferSuccessful;
}
I hope this is helpful :)

Downloading a File Via Angular $.http POST

I am trying to download a zipped file that my server generates in my UI. I am at a loss as to how to get the file to download though. We have it setup so that we can download with window.open where we pass the url and it opens a blank page. We need to do a POST where it has a body now. I havent seen a way to send that along with a window.open. Does anyone have any pointers on how i can get access to the returned file?
Here is my current code...
#RequestMapping(method = RequestMethod.POST, value = "/archives/download", consumes = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Integer> getArchive(HttpServletResponse response, #RequestBody List<GeneratedReport> reportList) {
System.out.println(reportList.get(0).getFileLocation());
List<String> filesToDownload = new ArrayList<>();
reportList.stream().forEach(e -> filesToDownload.add(e.getFileLocation()));
filesToDownloadAndZip(response, filesToDownload, "zipped_file.zip");
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=zipped_file.zip");
return new ResponseEntity<Integer>(200, HttpStatus.OK);
}
private void filesToDownloadAndZip(HttpServletResponse response, List<String> filesToDownload, String archiveFileName) {
try {
ByteArrayOutputStream baos = FileIO.CreateArchive(filesToDownload);
if (baos != null && baos.size() > 0) {
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=" + archiveFileName);
response.setContentType("application/zip");
response.setContentLength(baos.size());
baos.writeTo(response.getOutputStream());
response.flushBuffer();
} else {
LOG.debug("File was null or size 0, try again");
}
} catch(Exception ex)
{
LOG.debug(ex.getMessage());
}
}
The js i have is.....
$http.post('api/archives/download', $scope.downloadItems)
.success(function(data, status, headers, config) {
//I dont know what to do here..... :(
})

Uploading PDF from jsPDF with AJAX using binary data

I am attempting to pass a PDF I have generated on frontend javascript using jsPDF to a Spring Framework MVC backend. Below is the front end code I have written:
var filename = "thefile";
var constructURL = '/daas-rest-services/dashboard/pdfPrintUpload/' + filename;
var url = restService.getUrl(constructURL);
var fileBytes = btoa(pdf.output());
$http.post(url, fileBytes).success(function(data) {
console.log(data);
})
.error(function(e, a) {
console.log(e);
console.log(a);
});
The pdf variable has been generated properly and can confirm is opens correctly when calling pdf.save("filename"). Below is the Java code which has been written on the Spring MVC backend for this call:
#RequestMapping(method = RequestMethod.POST, value = "/pdfPrintUpload/{documentName}")
public #ResponseBody String postPrintDocument(#PathVariable String documentName, #RequestParam byte[] fileBytes) {
String methodName = "postPrintDocument";
if(logger.isLoggable(Level.FINER)){
logger.entering(CLASS_NAME, methodName);
}
String check;
if(fileBytes != null){
check = "not null";
} else {
check = "null ";
}
//Decoding the bytestream
//Save to file location
//return file location
String returnValue = "HI " + documentName + " " + check;
if (logger.isLoggable(Level.FINER)) {
logger.exiting(CLASS_NAME, methodName);
}
return returnValue;
}
Each time I make a request, I am getting 400 Errors telling me:
Error 400: Required byte[] parameter 'fileBytes' is not present
I can confirm in the request payload that a large amount of data is being transmitted, however the backend does not seem to want to accept the parameter.
The purpose of doing this is that I want to be able to get the data from the pdf and then decode it on the backend so I can later publish the pdf to a location on the server. Is there something I am missing in my code for these requests to keep failing, and is there an easier more efficient way to achieve this functionality?
The solution was changing the #RequestParam to #RequestBody. #RequestParam is a parameter which is sent in the path.
#RequestParam vs #PathVariable
Try using ng-file-upload. The link and the examples are available on the link
ng-file-upload
for the sever side code try using this
#RequestMapping(value = "/pdfPrintUpload")
#ResponseBody
public void postPrintDocument(#RequestParam("file") MultipartFile file) {
InputStream is = file.getInputStream();
OutputStream os = new FileOutputStream(/*path to save file*/);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
os.write(buffer, 0, length);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Excel Export in ASP.NET Web Service

I have this ASP.Net Web Application and in one of my Pages I'm using JQuery JQGrid, I want to be able to export the JQGrid to Excel Sheet, so using JavaScript I Collected the Values in an Array and then called a WebService to fill the values in a DataGrid, I successfully done all that, except for the exporting in the WebService no file download appears, and this is my WebService code:
[WebMethod]
public void GetData(object[] Values)
{
DT_ToFill.Columns.Add("CaseID");
DT_ToFill.Columns.Add("SR");
foreach (object Value in Values)
{
Dictionary<string, object> DictVals = new Dictionary<string, object>();
DictVals = (Dictionary<string, object>)Value;
string CaseID = DictVals["CaseID"].ToString();
string SR = DictVals["SR"].ToString();
object[] Obj = new object[2] { CaseID, SR };
DT_ToFill.Rows.Add(Obj);
}
ExportToExcel(DT_ToFill, Context.Response);
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
public void ExportToExcel(DataTable dt, HttpResponse Response)
{
GridView GridView1 = new GridView();
GridView1.DataSource = dt;
Response.Buffer = true;
Response.AddHeader("Content-Disposition", "inline;filename=Schedule_ExcelSheet.xls");
Response.Charset = "";
Response.ContentType = "application/ms-excel";
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.UTF8;
StringWriter sw = new StringWriter();
HtmlTextWriter ht = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
GridView1.DataBind();
GridView1.RenderControl(ht);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
public void VerifyRenderingInServerForm(Control control)
{
}
Help Please...
Thanks
Sounds like you are sending the excel file back as the response to the ajax request? If so, I don't think you can make a file download work through ajax.
Maybe send the data via ajax like you are doing now, but then do either a new window or an iframe (append it to document.body) and set the src to be a url that returns the excel file. That should trigger the file download. This is what I usually do.

Categories