I am working on classic ASP with WinCE OS. I want to upload a file from WinCE and Save in the local machine. Please share the necessary JScript function for file upload which i can put it in a include file. Thank you.
Better way is to use any JavaScript library.. like jQuery..
Here are the file upload examples..
http://pixelcone.com/jquery/ajax-file-upload-script/
How can I upload files asynchronously?
Cheers :)
I have no information about asp classic but I have used Asp.net and you can use asp to receive file in order to upload file from wince use can develop app using c# here is an example.
Its client WinCE Application Code Function Upload(string Path, String FileName) takes File Path and File Name as Input and Post it to web page
#region Upload
public bool Upload(string FilePath, string FileName)
{
string Url = "HTTP://test.mtsonweb.com/fileupload.ashx"; // Change it to your page name
string BytesConfirmedReceived = "";
int BytesSent = 0;
bool Ret = false;
ASCIIEncoding encoding = new ASCIIEncoding();
try
{
if (File.Exists(FilePath +"\\"+ FileName) == false) { return true; }
//FileInfo oInfo = new FileInfo(FilePath + "\\" + FileName);
//BytesSent = Convert.ToInt32(oInfo.Length.ToString());
Url += "?myfile=" + FileName.Trim();
FileStream fr = new FileStream(FilePath + "\\" + FileName, FileMode.Open);
BinaryReader r = new BinaryReader(fr);
byte[] FileContents = r.ReadBytes((int)fr.Length);
BytesSent = FileContents.Length;
r.Close();
fr.Close();
WebRequest oRequest = WebRequest.Create(Url);
oRequest.Method = "POST";
oRequest.Timeout = 15000;
oRequest.ContentLength = FileContents.Length;
Stream oStream = oRequest.GetRequestStream();
BinaryWriter oWriter = new BinaryWriter(oStream);
oWriter.Write(FileContents);
oWriter.Close();
oStream.Close();
WebResponse oResponse = oRequest.GetResponse();
BytesConfirmedReceived = new StreamReader(oResponse.GetResponseStream(),
Encoding.Default).ReadToEnd();
oResponse.Close();
if (BytesSent.ToString() == BytesConfirmedReceived.Trim())
{
Ret = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return Ret;
}
#endregion
Now of you page you can handle file uploaded using script whatever you want, I have used asp.net with c# as back-end and below is the source of page:
<%# WebHandler Language="C#" Class="FileUpload" %>
using System;
using System.Xml;
using System.Data;
using System.Web;
using System.IO;
using System.Text;
using System.Runtime.InteropServices;
using System.Drawing;
public class FileUpload : IHttpHandler
{
public void ProcessRequest(HttpContext oContext)
{
int BytesSent = 0;
//string LocalPath = #"C:\Inetpub\wwwroot\";
string MyFile = "";
try
{
MyFile = oContext.Request["myfile"].ToString().Trim();
MyFile = HttpContext.Current.Server.MapPath("~/Demo/Files/" +
ASCIIEncoding encoding = new ASCIIEncoding();
BytesSent = oContext.Request.TotalBytes;
Class1 obj = Class1.GetInstance();
obj.FileName = MyFile;
obj.FileLength = BytesSent;
byte[] InComingBinaryArray =
oContext.Request.BinaryRead(oContext.Request.TotalBytes);
obj.Data = InComingBinaryArray;
if (File.Exists(MyFile) == true)
{
File.Delete(MyFile);
}
FileStream fs = new FileStream(MyFile, FileMode.CreateNew);
BinaryWriter w = new BinaryWriter(fs);
w.Write(InComingBinaryArray);
w.Close();
fs.Close();
FileInfo oInfo = new FileInfo(MyFile);
long a = (long)BytesSent;
oContext.Response.Write(oInfo.Length.ToString());
}
catch (Exception err) { oContext.Response.Write(err.Message); }
}
public bool IsReusable { get { return true; } }
}
Related
I am working on a spring boot web application, where I want to upload multiple images of a product at a time along with other fields (for example product name, SKU code, category, tags, subcategory, etc). I have written code for RESTful API to upload multiple images and it is working perfectly for me. I tested API using postman and it is working fine. But, I don't know how to do it from the front end. I am showing you my front-end code below, where I am sending a single image to my controller using Ajax.
$("#file").change(function(){
var formData = new FormData();
var fileSelect = document.getElementById("file");
if(fileSelect.files && fileSelect.files.length == 1) {
var file = fileSelect.files[0];
formData.set("file",file,file.name);
}else{
$("#file").focus();
return false;
}
var request = new XMLHttpRequest();
try {
request.onreadystatechange=function() {
if(request.readyState==4) {
var v = JSON.parse(request.responseText);
if(v.status==="OK") {
alert("Product Image Uploaded Successfully")
document.getElementById('imagepath').value = v.response;
}
}
}
request.open('POST',"<%=AkApiUrl.testuploadfile%>");
request.send(formData);
} catch(e) {
swal("Unable to connect to server","","error");
}
});
As I told you, the above code is to send a single file at a time. I am showing you my API controller code also:
#RequestMapping(value = AkApiUrl.testuploadfile, method = { RequestMethod.POST, RequestMethod.GET }, produces = {MediaType.APPLICATION_JSON_VALUE }) public ResponseEntity<?> testuploadfile(HttpServletRequest request, #RequestParam("files") MultipartFile[] files) {
CustomResponse = ResponseFactory.getResponse(request);
String imgurl = "NA";
try {
String path = Constants.webmedia;
String relativepath = "public/media/";
System.out.println("Here is the image: ");
List<MultipartFile> multifile = Arrays.asList(files);
if( null != multifile && multifile.size()>0) {
for (int i=0; i < multifile.size(); i++) {
String filename = files[i].getOriginalFilename();
String extension = filename.substring(filename.lastIndexOf("."), filename.length());
int r = (int )(Math.random() * 500 + 1);
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddhhmmss");
Date date = new Date();
String formatdate = format.format(date);
formatdate = "ECOM" + formatdate + r;
byte[] bytes = files[i].getBytes();
BufferedOutputStream stream = new BufferedOutputStream( new FileOutputStream(new File(path + File.separator + formatdate + extension)));
stream.write(bytes);
stream.flush();
stream.close();
String newimgurl = relativepath + formatdate + extension;
imgurl = imgurl+"##"+newimgurl;
if(imgurl != null) {
CustomResponse.setResponse(imgurl);
CustomResponse.setStatus(CustomStatus.OK);
CustomResponse.setStatusCode(CustomStatus.OK_CODE);
}
}
}
} catch (Exception e) {
e.printStackTrace();
CustomResponse.setResponse(null);
CustomResponse.setStatus(CustomStatus.Error);
CustomResponse.setStatusCode(CustomStatus.Error_CODE);
CustomResponse.setResponseMessage(CustomStatus.ErrorMsg);
}
return new ResponseEntity<ResponseDao>(CustomResponse, HttpStatus.OK);
}
This API is working fine, I am getting desired response. But I do not know how should I implement this thing on the JSP page. Please, any suggestions would be appreciated.
I need to store the image in my database in byte[]
I am sending the image from Javascript to mvc controller using ajax
In my javascript
var files = $("#MyImage").get(0).files;
formData.append('files', files);
in my MVC Controller
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
Is it a correct way to store the image or I am doing this wrong?
please suggest
You can post HttpPostedFileBase on your razor.
if (upload != null)
{
using (var inputStream = upload.InputStream)
{
var memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
var data = memoryStream.ToArray();
}
The method signature should be like this
[HttpPost]
public ActionResult Foo(HttpPostedFileBase upload)
{
}
And your razor side:
#using (Html.BeginForm("Foo", "ControllerName", FormMethod.Post, new { #enctype = "multipart/form-data" }))
{
}
I can't get it to work to download an excel file that was created by closedxml through web API.
If I save the file on the server it looks good, but as soon as I put it in a stream and return it to the web api, then only a corrupt file is recieved in the browser.
As suggested on several posts I use httpResponseMessage, but also in the browser the filename in the header never arrives.
We are using:
"Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net461
"ClosedXML" version="0.88.0" targetFramework="net461"
WebAPI Code:
var wb = new XLWorkbook();
var ws = wb.Worksheets.Add("Parcel List");
MemoryStream fs = new MemoryStream();
wb.SaveAs(fs);
fs.Position = 0;
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(fs.GetBuffer());
result.Content.Headers.ContentLength = fs.Length;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "List" + "_" + DateTime.Now.ToShortDateString() + ".xlsx"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
Here the javascript code:
context.$http.post(config.get_API_URL() + 'api_call', excel_list,
{responseType: 'application/octet-stream'})
.then(
success_function,
error_function)
}
success_function:
function(response) {
var headers = response.headers;
var blob = new Blob([response.body],
{type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
);
window.open(window.URL.createObjectURL(blob));
}
I could successfully download a workbook with this code now:
using ClosedXML.Excel;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace ClosedXML.Extensions.WebApi.Controllers
{
public class ValuesController : ApiController
{
public IHttpActionResult Get(int id)
{
return new TestFileActionResult(id);
}
}
public class TestFileActionResult : IHttpActionResult
{
public TestFileActionResult(int fileId)
{
this.FileId = fileId;
}
public int FileId { get; private set; }
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage response = null;
var ms = new MemoryStream();
using (var wb = new XLWorkbook())
{
var ws = wb.AddWorksheet("Sheet1");
ws.FirstCell().Value = this.FileId;
wb.SaveAs(ms);
ms.Seek(0, SeekOrigin.Begin);
response = new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StreamContent(ms);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
response.Content.Headers.ContentDisposition.FileName = "test.xlsx";
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.Content.Headers.ContentLength = ms.Length;
ms.Seek(0, SeekOrigin.Begin);
}
return Task.FromResult(response);
}
}
}
Have a look at the Mvc extension package at https://www.nuget.org/packages/ClosedXML.Extensions.Mvc/
PS: I've been told I have to disclaim this everytime. I'm the maintainer of ClosedXML and ClosedXML.Extensions.Mvc.
The problem seems to be that the response type for the web api call has to be {responseType: 'arraybuffer'} instead of {responseType: 'application/octet-stream'}
context.$http.post('api-url', excel_list,
{responseType: 'arraybuffer'})
.then(
success_function,
error_function)
}
Thanks anyhow for your quick help
In our mobile application (cordova+html4) we have a requirement to display the PDF from a stream. We have a service which returns pdf stream. We would like to store that stream to a temp folder location of the mobile and display the PDF.
The below sample java sample java code does the exact thing what I need. But how can I achive this functionality on java script? I mean reading a binary stream in java script.
String fileURL = "https://1/////4/xyz";
String saveDir = "D:/Works";
try {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url
.openConnection();
httpConn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
httpConn.setRequestProperty("TOKEN",
"ghZtxnPfpJ63FgdT/59V+5zFTKHRdwm6rIfGJC+0B5W5CJ9pG33od7l+/L6S8R56");
int responseCode = httpConn.getResponseCode();
System.out.println("Reseponse Code = " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn
.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(
saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out
.println("No file to download. Server replied HTTP code: "
+ responseCode);
}
httpConn.disconnect();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thre's two libraries that you may want to have a look at :
jsPDF if you're trying to generate pdf from javascript and
pdf.js if you're trying to implement a pdf viewer in your interface.
One of those two should do the trick for you.
In my JSP, I have a button named "Download Zip file". When I click the button, I want to fetch data from the database and write it into a JS file and keep it inside a folder and download folder in ZIP format. I am using struts2.
How can I do this?
One way is to serve binary data from a servlet. Something like this:
byte[] zipFileBytes = ...;// generate the zip file and get the bytes
response.setContentType("application/octet-stream");
response.getOutputStream().write(zipFileBytes );
Then use a standard anchor element to download the file:
<a src="url to your servlet">download the file</a>
You might need to play with this a little bit to match your exact use case.
Try this : code to download file as a Zip
ServletOutputStream servletOS = null;
String zipFileName = null;
try {
servletOS = response.getOutputStream();
final ResourceResolver resolver = request.getResourceResolver();
zipFileName = FileDownloadHelper.getDownloadZipFileName();
response.setContentType("application/zip");
response.addHeader("Content-Disposition", "attachment; filename=" + zipFileName);
servletOS.write(FileDownloadHelper.prepareZipDownloadOutputStream(servletOS, documentUrls));
} finally {
if (servletOS != null) {
servletOS.flush();
servletOS.close();
}
}
public static byte[] prepareZipDownloadOutputStream(final ServletOutputStream outputStream,
final List<String> docUrls) throws IOException {
final byte[] buf = new byte[2048];
String fileName;
ZipOutputStream zipOutputStream = null;
InputStream isInputStream = null;
try {
zipOutputStream = new ZipOutputStream(outputStream);
for (final String docUrl : docUrls) {
LOGGER.info("Reading file from DAM : " + docUrl);
// read this file as input stream
isInputStream = new FileInputStream(docUrl);
if (isInputStream != null) {
fileName = getFileNameFromDocumentUrl(docUrl);
// Add ZIP entry to output stream.
zipOutputStream.putNextEntry(new ZipEntry(fileName));
int bytesRead;
while ((bytesRead = isInputStream.read(buf)) != -1) {
zipOutputStream.write(buf, 0, bytesRead);
}
zipOutputStream.closeEntry();
} e
}
} finally {
if (zipOutputStream != null) {
zipOutputStream.flush();
zipOutputStream.close();
}
if (isInputStream != null) {
isInputStream.close();
}
}
LOGGER.info("Returning buffer to be written to response output stream");
return buf;
}
public static String getFileNameFromDocumentUrl(final String docUrl) {
return docUrl
.substring(docUrl.lastIndexOf("/") + 1, docUrl.length());
}