Uploading byte array to MYSQL shows empty field (nothing uploaded?) - serialization

I've been trying to write a script which opens a file with UniFileViewer, sets a path to the file and passes it to various methods which serialize it and upload it to my MYSQL server. When I run the script it executes without problems but the result is 0 bytes uploaded to the database. I must have missed something here...
public class FileOpen : MonoBehaviour
{
public UITexture ProfilePic;
public static Texture2D tex = null;
public static String selectedFilePath;
void openFile()
{
UniFileBrowser.use.OpenFileWindow(OpenFile);
}
public static Texture2D LoadPNG(string selectedFilePath)
{
byte[] fileData;
fileData = File.ReadAllBytes(selectedFilePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
return tex;
}
//OPENS THE FILE AND SENDS IT TO THE SERVER
void OpenFile(string filePath)
{
selectedFilePath = filePath;
LoadPNG(selectedFilePath);
Texture2D uploadFile = tex;
byte[] bytes = uploadFile.EncodeToPNG();
string fileToSend = Convert.ToBase64String(bytes);
string[] datas = new string[1];
datas[0] = fileToSend;
LoginPro.Manager.ExecuteOnServer("SaveFile", SendToServer_Success, SendToServer_Error, datas);
}

Related

Is it possible to cancel a call to speakTextAsync?

I'm using the javascript SDK of Microsoft Speech Synthesizer and calling speakTextAsync to convert text to speech.
This works perfectly, but sometimes the text is long and I want to be able to cancel in the middle, but I cannot find any way to do this. The documentation doesn't seem to indicate any way to cancel. The name speakTextAsync suggests that it returns a Task that could be cancelled, but in fact the method returns undefined, and I can't find any other way to do this. How can this be done?
Seems there is no way to stop it when it is speaking. But actually,as a workaround, you can just download the audio file and play the file yourself so that you can control everything. try the code below:
import com.microsoft.cognitiveservices.speech.*;
import com.microsoft.cognitiveservices.speech.audio.AudioConfig;
import java.nio.file.*;
import java.io.*;
import javax.sound.sampled.*;
public class TextToSpeech {
public static void main(String[] args) {
try {
String speechSubscriptionKey = "key";
String serviceRegion = "location";
String audioTempPath = "d://test.wav"; //temp file location
SpeechConfig config = SpeechConfig.fromSubscription(speechSubscriptionKey, serviceRegion);
AudioConfig streamConfig = AudioConfig.fromWavFileOutput(audioTempPath);
SpeechSynthesizer synth = new SpeechSynthesizer(config, streamConfig);
String filePath = "....//test2.txt"; // .txt file for test with long text
Path path = Paths.get(filePath);
String text = Files.readString(path);
synth.SpeakText(text);
Thread thread = new Thread(new Speaker(audioTempPath));
thread.start();
System.out.println("play audio for 8s...");
Thread.sleep(8000);
System.out.println("stop play audio");
thread.stop();
} catch (Exception ex) {
System.out.println("Unexpected exception: " + ex);
assert (false);
System.exit(1);
}
}
}
class Speaker implements Runnable {
private String path;
public String getText(String path) {
return this.path;
}
public Speaker(String path) {
this.path = path;
}
public void run() {
try {
File file = new File(path);
AudioInputStream stream;
AudioFormat format;
DataLine.Info info;
Clip clip;
stream = AudioSystem.getAudioInputStream(file);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}

Apache Tika - read chunk at a time from a file?

Is there any way to read chunk at a time (instead of reading the entire file) from a file using Tika API?
following is my code. As you can see I am reading the entire file at once. I would like to read chunk at a time and create a text file the content.
InputStream stream = new FileInputStream(file);
Parser p = new AutoDetectParser();
Metadata meta =new Metadata();
WriteOutContentHandler handler = new WriteOutContnetHandler(-1);
ParseContext parse = new ParseContext();
....
p.parse(stream,handler,meta, context);
...
String content = handler.toString();
There's (now) and Apache Tika example which shows how you can capture the plain text output, and return it in chunks based on the maximum allowed size of a chunk. You can find it in ContentHandlerExample - method is parseToPlainTextChunks
Based on that, if you wanted to output to a file instead, and on a per-chunk basis, you'd tweak it to be something like:
final int MAXIMUM_TEXT_CHUNK_SIZE = 100 * 1024 * 1024;
final File outputDir = new File("/tmp/");
private class ChunkHandler extends ContentHandlerDecorator {
private int size = 0;
private int fileNumber = -1;
private OutputStreamWriter out = null;
#Override
public void characters(char[] ch, int start, int length) throws IOException {
if (out == null || size+length > MAXIMUM_TEXT_CHUNK_SIZE) {
if (out != null) out.close();
fileNumber++;
File f = new File(outputDir, "output-" + fileNumber + ".txt);
out = new OutputStreamWriter(new FileOutputStream(f, "UTF-8"));
}
out.write(ch, start, length);
}
public void close() throws IOException {
if (out != null) out.close();
}
}
public void parse(File file) {
InputStream stream = new FileInputStream(file);
Parser p = new AutoDetectParser();
Metadata meta =new Metadata();
ContentHandler handler = new ChunkHandler();
ParseContext parse = new ParseContext();
p.parse(stream,handler,meta, context);
((ChunkHandler)handler).close();
}
That will give you plain text files in the given directory, of no more than a maximum size. All html tags will be ignored, you'll only get the plain textual content

Adding PImage to an ArrayList of PImage using filenames from a text file?

So what I'm trying to do is receive the name of a text file that contains a list of filenames of a sequence of images that I have stored in a separate folder. So I get the path to the actual image files using a scanner and scan through each line of the text file, therefore reading the names of the image files in the context of their actual location. Note that the text file and folder of the images have the same path. My question is how do I get these images into my ArrayList of PImages so I can then later load and display them sequentially in a repeating loop using draw()?
private List <PImage> myImage;
private int myFrameRate, myImageNumber;
private Boolean myRunningStatus;
public AnimationPanel(String path, String textFilename) throws FileNotFoundException {
myImage = new ArrayList <PImage>();
Scanner scanner = new Scanner(new File(path + textFilename));
myFrameRate = 20;
myRunningStatus = true;
myImageNumber = 0;
while(scanner.hasNextLine()){
loadImage(path + scanner.nextLine());
myImageNumber++;
}
scanner.close();
}
public void play() {
myRunningStatus = true;
}
public void pause() {
myRunningStatus = false;
}
public void setup() {
size(300, 200);
frameRate(myFrameRate);
}
public void draw() {
background(255);
if(myRunningStatus == true){
image(myImage.get(myImageNumber), 0, 0);
}
}
I think (untested)
while(scanner.hasNextLine()){
PImage p = loadImage(path + scanner.nextLine());
myImage.add(p);
}

Wicket : FileUploadPage doesnt refresh the filepath

again, i got a problem with wicket. Im trying to upload data with my Class "FileUploadPanel", which is implemented on another Page "Class A":
Class A
...
/* uploadfields for Picture and Video */
ArrayList<String> picExt = new ArrayList<String>();
ArrayList<String> videoExt = new ArrayList<String>();
picExt.add("jpg");
videoExt.add("mp4");
final FileUploadPanel picUpload = new FileUploadPanel("picUpload", "C:\\", picExt);
final FileUploadPanel videoUpload = new FileUploadPanel("videoUpload", "C:\\", videoExt);
final Form form = new Form("form"){
protected void onSubmit() {
...
// Save the path of Video and Picture into Database
table.setVideo(videoUpload.getFilepath());
table.setPicture(picUpload.getFilepath());
...
}
...
Class FileUploadPanel
public class FileUploadPanel extends Panel {
private static final long serialVersionUID = -2059476447949908649L;
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "C:\\";
private String filepath = "";
private List<String> fileExtensions;
/**
* Constructor of this Class
* #param id the wicket-id
* #param uploadFolder the folder, in which the File will be uploaded
* #param fileExtensions List of Strings
*/
public FileUploadPanel(String id, String uploadFolder, List<String> fileExtensions) {
super(id);
this.UPLOAD_FOLDER = uploadFolder;
this.fileExtensions = fileExtensions;
add(fileUpload = new FileUploadField("fileUpload"));
}
#Override
public void onComponentTag(ComponentTag tag){
// If no file is selected on startup
if(fileUpload.getFileUpload() == null){
return;
}
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file,
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
filepath = UPLOAD_FOLDER + uploadedFile.getClientFileName();
// if file in upload-folder already exists -> delete it
if (newFile.exists()) {
newFile.delete();
}
try {
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
} catch (Exception e) {
throw new IllegalStateException("Error");
}
}
}
public String getFilepath() {
return filepath;
}
}
Well, if i use the submit-Button on my "Class A", the Pic and Video get saved on C:\, which is quite good so far. I thought i finally get along with wicket, but i cheered too soon...
Problem: The correct path is not saved in the Database, which is handled in the Form of "Class A"
I really dont get it, because the onComponentTag(...) of my FileUploadPanel must be executed when using the submit-button. Thats because i added some validations like "picture must be a JPG or wont be saved" in onComponentTag(...) - and that worked. So im sure, the onComponentTag(...) is executed when the Submit-Button of the Form is used, which also means the filepath should be up-to-date.
What is it im doin wrong this time?
Thank in Advance!
Greeting
V1nc3nt
You are using
File newFile = new File(UPLOAD_FOLDER +
uploadedFile.getClientFileName());
this code to create a new File.
Instead of it you can try this one :
File file = new File(UPLOAD_FOLDER ,
uploadedFile.getClientFileName());
And then get the absolute path and save it:
newFile.getAbsolutePath();

Using wcf how to upload a image

using wcf/wcf web services to upload a images give me with example?
In my project i want to upload image by using WCF
Basically you should use WCF streaming.
[ServiceContract]
public interface ITransferService
{
[OperationContract]
void UploadFile(RemoteFileInfo request);
}
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"C:\\upload\\";
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create,
FileAccess.Write, FileShare.None))
{
//read from the input stream in 65000 byte chunks
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
// save to output stream
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
The easiest way is to convert the image to a byte array before sending it, and then converting it back to an image on the destination site.
Here are two methods for doing just that:
public byte[] ImageToByteArray( Image image)
{
var ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
public static Image ByteArrayToImage(byte[] byteArray)
{
var ms = new MemoryStream(byteArray);
return Image.FromStream(ms);
}
That means your web service can have a method something like this:
public void UploadImage( byte[] imageData )
{
var image = ByteArrayToImage( imageData );
//save image to disk here, or do whatever you like with it
}