Download zip file ajax response in java spring mvc - javascript

I'm trying to download multiple files as a zip file, I'm posting an AJAX request with my form data to the server, which compresses the file and returns it for the client to download, with the following code:
function downloadDocs(arrays) {
console.log("Call download");
var text = JSON.stringify(arrays);
$("#selectedList").val(text);
var formData = new FormData($("#formSelectionFiles")[0]);
formData.append("candidateId", $("#candidateId").val());
$.ajax({
type : "POST",
url : "${contextPath}/ajax/candidate/onboarding/multidownload?data=",
contentType: false,
processData: false,
data : formData,
success : function(data) {
var blob = new Blob([data], {type: "application/octet-stream"});
//URL.createObjectURL(blob)
saveAs(blob, "download.zip");
console.log("SUCCESS : " + data);
},
error : function(e) {
console.log("ERROR : ", e);
}
});
}
My Controller to mapping URL:
#RequestMapping(value = "/ajax/candidate/onboarding/multidownload", method = RequestMethod.POST
, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
public #ResponseBody byte[] downloadCandidateDoc(HttpServletRequest req, HttpServletResponse res, Long candidateId,
String selectedList) {
System.out.println(selectedList);
if (TextUtils.isEmpty(selectedList)) {
return null;
}
final Type token = (Type) new TypeToken<ArrayList<DownloadItem>>() {
}.getType();
final GsonBuilder builder = new GsonBuilder();
final Gson gson = builder.create();
final List<DownloadItem> fileList = gson.fromJson(selectedList, token);
return candidateService.downloadCandidateDocs(res, String.valueOf(candidateId), fileList);
}
My service:
public byte[] downloadCandidateDocs(HttpServletResponse res, String id, List<DownloadItem> files) {
final String candidateDir = MediaUtil.getAbsolutePath("upload_candidate", id);
List<String> fileList = new ArrayList<>();
if (files != null && !files.isEmpty()) {
for (DownloadItem str : files) {
System.out.println("file name: " + str.getUrl());
fileList.add(new File(candidateDir, str.getUrl()).getAbsolutePath());
}
}
try {
return FileStreamUtil.zipfiles(fileList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
This code is used to generate the zip file:
public static byte[] zipfiles(List<String> files) throws IOException {
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
byte bytes[] = new byte[2048];
for (String fileName : files) {
File fileToZip = new File(fileName);
FileInputStream fis = new FileInputStream(fileName);
ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
zos.putNextEntry(zipEntry);
int bytesRead;
while ((bytesRead = fis.read(bytes)) != -1) {
zos.write(bytes, 0, bytesRead);
}
zos.closeEntry();
fis.close();
fis.close();
}
zos.close();
return baos.toByteArray();
}
And here's the result I receive in the output stream:

Related

Upload file failed to save in Database

public JsonResult SaveAttachment(string buyerCode)
{
Dictionary<int, CheckSessionData> IDictionary = CheckSessionData.GetSessionValues();
long companyId = (long)IDictionary[1].Id;
long userId = (long)IDictionary[3].Id;
var buyer = DB.Buyers.FirstOrDefault(x => x.Code == buyerCode);
string basePath = "~/Upload/BuyerAttachment/";
string path = Server.MapPath(basePath);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
HttpFileCollectionBase files = Request.Files;
List<string> filePathList = new List<string>();
for (int i = 0; i > files.Count; i++)
{
HttpPostedFileBase file = files[i];
var date = DateTime.Now.ToString().Replace('/', '_');
string FilePath = Path.Combine(path, date.Replace(':', ' ') + file.FileName);
file.SaveAs(FilePath);
filePathList.Add(FilePath);
}
foreach (var item in filePathList)
{
var buyerAttachment = new Buyer_Attachment();
buyerAttachment.BuyerId = buyer.BuyerId;
buyerAttachment.DateOfEntry = DateTime.Now;
buyerAttachment.EntryBy = userId;
buyerAttachment.AttachmentURL = path;
DB.Buyer_Attachment.Add(buyerAttachment);
}
try
{
DB.SaveChanges();
}
catch (Exception)
{
return Json(false, JsonRequestBehavior.AllowGet);
}
return Json(true);
}
}
function SaveAttachment(code) {
var files = $("#CustomerAttachment").get(0).files;
var fileData = new FormData();
for (var i = 0; i < files.length; i++) {
fileData.append("fileInput", files[i]);
}
$.ajax({
type: "POST",
url: "/BuyerSimple/SaveAttachment?buyerCode="+code,
dataType: "json",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: fileData,
success: function (result, status, xhr) {
filePathList = result;
$('#AttachmentPathList').val(result);
},
error: function (xhr, status, error) {
alert(status);
}
});
}

How to fetch form with file and recieve it on net core?

I try to fetch and recieve data in my net core app.
This code works:
[HttpPost]
public JsonResult Post([FromBody] User user)
{
var s = HttpContext.Request.QueryString;
Console.WriteLine($"name: {user.Name}, age: {user.Age}");
return Json(user);
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
const url = "http://localhost:5000/Home/Post";
const user = {Name: 'valenok', Age: 25 };
fetch(url, {
method: 'POST', // or 'PUT'
body: JSON.stringify(user),
headers: {
'Accept': 'application/json; charset=utf-8',
'Content-Type': 'application/json;charset=UTF-8'
}
}).then(res => res.json())
.then(response => console.log('Success:', JSON.stringify(response)))
.catch(error => console.error('Error:', error));
But if I try to send object {file and string} i recieve just a string field ImageDTO.FileName. ImageDTO.Image is null.
Here is the code:
[HttpPost]
public async Task AddFile(ImageDTO img)
{
Console.WriteLine($"FileName: {img.Image}");
Console.WriteLine($"FileName: {img.FileName}");
if (img.Image == null)
{
Console.WriteLine("NULL");
}
try
{
string path = "/Files/" + img.FileName;
using (var fileStream = new FileStream(appEnvironment.WebRootPath + path, FileMode.Create))
{
Console.WriteLine($"IMAGE: {img.Image}");
await img.Image.CopyToAsync(fileStream);
}
return Json($"File saved to{path}");
}
catch (System.Exception ex)
{
Console.WriteLine($"Something wrong! {ex.Message}");
return Json($"Something wrong! {ex.Message}");
}
}
clientside:
class FileDownloadForm1 extends React.Component {
state = {
file: null,
title: null,
};
onFileChange = (e) => {
this.setState({file: e.target.value})
console.log(this.state.file);
};
onTitleChange = (e) => {
this.setState({title: e.target.value})
console.log(this.state.title);
};
onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
const url = "http://localhost:5000/Home/AddFile";
formData.append("FileName", this.state.title);
formData.append("Image", this.state.file);
console.log(this.state.file);
console.log(this.state.title);
let xhr = new XMLHttpRequest();
xhr.open('POST', url);
xhr.send(formData);
}
render() {
return (
Choose file to upload
Simplae label
{/* {this.onTitleChange(e)}} name="title">*/}
Submit
);
onSubmit method i tried like this and result was the same:
code>
(with headers or not)
onSubmit = async (e) => {
e.preventDefault();
const formData = new FormData();
const url = "http://localhost:5000/Home/AddFile";
formData.append("FileName", this.state.title);
formData.append("Image", this.state.file);
const result = await fetch(url, {
method: 'POST',
body: formData
});
const response = await result.json();
console.log(response);
}
console output:
FileName: 123
NULL
IMAGE:
Something wrong! Object reference not set to an instance of an object.
I check this How to upload image from React to ASP.NET Core Web API?
but... if i asking it`s not worked for me. help
You can try to use e.target.files[0] to get the selected file, like below.
onFileChange = (e) => {
this.setState({ file: e.target.files[0] });
console.log(this.state.file);
};

Prints out Gibberish PDF file. Angular 6

this is how the binary file looks like.
This is how im subscribing to the method that fetches pdf blob file
public downloadDoc(token: any, docNumber: number) {
this.loading = true;
this._docService.getDocumentStreams(token, docNumber).subscribe(res => {
this.loading = false;
let file = new Blob([res._body], {
type: 'application/pdf'
});
var fileURL = URL.createObjectURL(file);
console.log(res)
window.open(fileURL);
}, (error => {
console.log(`failed to download document: ${error}`);
}))
}
heres the method in service
public getDocumentStreams(token: any, docNumber: number): Observable < any > {
const body = {
'DocNo': docNumber,
'StreamNo': 0
};
const headers = new Headers();
headers.append('Content-Type', 'application/json');
headers.append('Accept', 'application/json');
headers.append('TenantName', 'idl');
headers.append('UseToken', '1');
headers.append('Authorization', 'Basic ' + window.btoa('webapi' + ':' + token));
headers.append('responseType', 'arraybuffer'
as 'json');
return this.http.post(`${this._therefore_apiBase}/GetDocumentStreamRaw`, body, {
headers: headers
}).pipe(
map((response) => {
return response;
}));
}
This prints out a gibberish pdf file what could be the problem

Connecting a simple WebSocket (Java/Javascript)

I'm trying to connect my javascript WebSocket to the backend.
I'm using this HTTP Hijack https://gist.github.com/missedone/76517e618486db746056
My Java code get's the response correctly System.out.println(response); (so there's connection) but this is not what I want.
I want to connect the backend (java) to the frontend (jquery/javascript) so I can send commands though the terminal instead of the current implementation
I'm only missing a way to connect this HttpHijack in the backend to my WebSocket in the front end.
Any help?
Java
public String execConsole(String containerName) {
Settings settings = Settings.getSettings();
Container container = getContainer(containerName);
//exec
ExecCreateCmdResponse execCreateResp = dockerClient().execCreateCmd(container.getId()).withCmd("bash")
.withAttachStderr(true).withAttachStdout(true).withAttachStdin(true).withTty(false).exec();
HashMap<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/json");
HttpHijack ws = null;
try {
ws = new HttpHijack(new URI("http://" + settings.getDockerIP() +":"+ settings.getDockerPort() +"/v1.19/exec/" + execCreateResp.getId() + "/start"));
} catch (URISyntaxException e) {
e.printStackTrace();
}
String payload = "{\"Detach\": false,\"Tty\": false}";
try {
ws.post(headers, payload);
} catch (IOException e) {
e.printStackTrace();
}
String request = "date > /tmp/nick2; cat /tmp/nick2; exit $?;";
InputStream input = null;
try {
input = ws.send(request);
} catch (IOException e) {
e.printStackTrace();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
InspectExecResponse execResp = dockerClient().inspectExecCmd(execCreateResp.getId()).exec();
System.out.println("exec inspect: {}" + execResp);
try {
String response = IOUtils.readLines(input).toString();
System.out.println(response);
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
Javascript
$('#btnConnect').click(function () {
$.ajax({
url: '/connect-console',
type: 'post',
data: {containerName: containerName},
success: function (url) {
$('#connectDiv').hide();
$('#terminalDiv').show();
term = new Terminal({
screenKeys: true,
useStyle: true,
cursorBlink: true
});
ws = new WebSocket(url,true);
ws.binaryType = 'arraybuffer';
term.on('data', function (data) {
ws.send(data);
});
term.open(document.getElementById("terminal"), true);
ws.onopen = function() {
console.log('ws connected');
};
ws.onerror = function() {
console.log('ws error');
};
ws.onclose = function() {
console.log('ws closed');
};
ws.onmessage = function(evt) {
var decoder = new TextDecoder('utf-8');
var data = decoder.decode(evt.data);
term.write(data);
};
}
});
});

E/AndroidRuntime FATAL EXCEPTION: main PID: 17633

When I try to register a new user in my app, throw mySQL db the application doesn't work and sends this error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.io.biolite6, PID: 17633
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object
reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.(JSONObject.java:156)
at org.json.JSONObject.(JSONObject.java:173)
at com.example.io.biolite6.BackgroundsTask.onPostExecute(BackgroundsTask.java:114)
at com.example.io.biolite6.BackgroundsTask.onPostExecute(BackgroundsTask.java:30)
at android.os.AsyncTask.finish(AsyncTask.java:636)
at android.os.AsyncTask.access$500(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:653)
at android.os.Handler.dispatchMessage(Handler.java:111)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
I/Process: Sending signal. PID: 17633 SIG: 9
public class BackgroundsTask extends AsyncTask<String,Void,String> {
String register_url = "http://192.168.1.104/loginapp/register.php";
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundsTask(Context ctx)
{
this.ctx = ctx;
activity = (Activity) ctx;
}
#Override
protected void onPreExecute()
{
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Connecting to server...");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params[0];
if (method.equals("register"))
{
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection =(HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line = bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registration Success", message,code);
}
else if (code.equals("reg_false"))
{
showDialog("Registration Failed",message,code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title, String message, String code)
{
builder.setTitle(title);
if (code.equals("reg_true")||code.equals("reg_false"))
{
builder.setMessage(message);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
}

Categories