简体   繁体   中英

Cross Origin requests at server side

Hi I am facing issue in cross origin requests at server side when trying to open file which is retrieved from database using java.I am unaware of this cross orgin requests.When file is clicked then it is giving error as

jquery.min.js:4 XMLHttpRequest cannot load file:///C:/Users/JR00432239/Desktop/trial/src/temp/filetest1.docx. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https.

Can anyone please help me to resolve this issue.

Here is my java code:

package fileretrieve;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import org.apache.tomcat.util.http.fileupload.IOUtils;

import dbConnection.Dbconn;

@MultipartConfig
public class FileRetrieve extends HttpServlet {



    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
          response.setContentType("text/plain");

          PrintWriter out = response.getWriter();        
          String onelevel=request.getParameter("onelevel"); 







          Connection conn = null; // connection to the database
          String message = null;
          Statement st = null;// message will be sent back to client



          try {
              // connects to the database
              conn = Dbconn.getConnection();
                st = conn.createStatement();

                 PreparedStatement ps=conn.prepareStatement("select data from files1 where board=?");
                 ps.setString(1,onelevel);                   
                 //out.print("<table width=25% border=1>");
                // out.print("<center><h1>Result:</h1></center>");
                 ResultSet rs=ps.executeQuery();                
                 /* Printing column names */
                 ResultSetMetaData rsmd=rs.getMetaData();
                 int count=0;
                 while(rs.next())
                    {
                     count=count+1;
                     FileOutputStream fos = new FileOutputStream("C:\\Users\\JR00432239\\Desktop\\trial\\src\\temp\\filetest"+count+".docx");
                     fos.write(rs.getBytes(1));
                     fos.close();

//                 out.print("<tr>");
//                 out.print("<td>"+rsmd.getColumnName(1)+"</td>");
//                    out.print("<td><a href=\"file:///C:/Users/JR00432239/Desktop/trial/src/temp/test.pdf\" target=\"_self\">"+count+"</a></td></tr>");
//                    getServletContext().getRequestDispatcher("/home.html").forward(request, response);
                     System.out.println("writing...");
                     response.getWriter().write("{\"name\":\""+count+"\",\"path\":\"C:/Users/JR00432239/Desktop/trial/src/temp/filetest"+count+".docx\"}");



                 }


//                 out.print("</table>");
//                 


          }catch (Exception e2)
            {
                e2.printStackTrace();
            }

          finally{

//            request.setAttribute("data", data);
//            RequestDispatcher rd =request.getRequestDispatcher("userview.jsp");
//            

              out.close();
            }


          // forwards to the message page
        //  getServletContext().getRequestDispatcher("/home.html").forward(request, response);
   }

}   

Here is my html code: Submit

Here is my javascript page:

$("#retrieve").click(function(){

     $.ajax({
            url : 'FileRetrieve',
            method:"POST",
            data : {
                onelevel : $('#onelevel').val()
            },

            crossDomain: true,
            success : function(responseText) {
                var data=JSON.parse(responseText)
                $("#files_data").html('')
                $("#files_data").html('<table><tr><td><button onclick="getFile()">'+data.name+'</button></td></tr></table>')

            },
            error: function(XMLHttpRequest, textStatus, errorThrown) { 
                alert("Status: " + textStatus); alert("Error: " + errorThrown); 
            }
        });
     return false;
 });

If you're using chrome, as a simple solution try a chrome extention like Allow-Control-Allow-Origin:* https://chrome.google.com/webstore/detail/nlfbmbojpeacfghkpbjhddihlkkiljbi?utm_source=chrome-app-launcher-info-dialog

if not fixed, run chrome using command line with the flag

path/to/chrome.exe --allow-file-access-from-files

or just switch to firefox and check whether the issue is still there

this would be a quick-fix only in the development

EDIT

As far as I know, best thing you can do is make the files available in http server and access them using http protocol.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM