Files
imexmobile/util/local-document-upload.utility.js
2022-05-10 15:00:59 -07:00

89 lines
2.2 KiB
JavaScript

import axios from "axios";
import { store } from "../redux/store";
import * as MediaLibrary from "expo-media-library";
import * as ImageManipulator from "expo-image-manipulator";
export const handleLocalUpload = async ({ ev, context }) => {
const { onError, onSuccess, onProgress, filename, mediaId } = ev;
const { jobid, invoice_number, vendorid, callbackAfterUpload } = context;
var options = {
headers: { "X-Requested-With": "XMLHttpRequest" },
onUploadProgress: (e) => {
if (onProgress) onProgress({ percent: (e.loaded / e.total) * 100 });
},
};
const formData = new FormData();
formData.append("jobid", jobid);
if (invoice_number) {
formData.append("invoice_number", invoice_number);
formData.append("vendorid", vendorid);
}
const imageData = await MediaLibrary.getAssetInfoAsync(mediaId);
const newFile = await (await fetch(imageData.localUri)).blob();
let thumb;
let fileData = {
uri: null,
type: null,
name: null,
};
if (newFile.type === "image/heic") {
try {
thumb = await ImageManipulator.manipulateAsync(imageData.uri, [], {
format: "jpeg",
base64: true,
compress: 0.75,
});
const name = newFile.data.name.split(".");
name.pop();
fileData = {
uri: thumb.uri,
type: newFile.type,
name: name.join("") + ".jpeg",
};
} catch (error) {
console.log(error);
}
} else {
fileData = {
uri: imageData.localUri,
type: newFile.type,
name: filename,
};
}
formData.append("file", fileData);
const bodyshop = store.getState().user.bodyshop;
try {
const imexMediaServerResponse = await axios.post(
`${bodyshop.localmediaserverhttp}/${
invoice_number ? "bills" : "jobs"
}/upload`,
formData,
{
...options,
}
);
if (imexMediaServerResponse.status !== 200) {
if (onError) {
console.log(imexMediaServerResponse);
onError(imexMediaServerResponse.statusText);
}
} else {
onSuccess && onSuccess();
}
if (callbackAfterUpload) {
callbackAfterUpload();
}
} catch (error) {
console.log("Error uploading documents:", error);
}
};