Uploadify solution that cannot be uploaded under Firefox, java version (Spring + SpringMVC + MyBatis) detailed solution

Source: Internet
Author: User

Uploadify solution that cannot be uploaded under Firefox, java version (Spring + SpringMVC + MyBatis) detailed solution
Because of the technical selection, in a product, I chose uploadify because it has a complete technical documentation description (http://www.uploadify.com/documentation ), the only drawback is that the example in the official document is written in php. However, it is difficult to find a suitable example for our students who use the Java language. Especially when you encounter browser compatibility problems, after a long time, you finally find that you have compiled the content on the Internet, and the problem still persists, the explanation is not detailed.

Next I will share with you the symptoms and solutions I have encountered, hoping to help you quickly solve problems in Java projects.

Error:

In IE and Google browsers, when uploadify is used to upload files, it is normal that the files can be uploaded successfully. When Firefox browser is used, it cannot be uploaded either. No response. It's really disappointing.

Solution:

  1. I searched Baidu for "uploadify compatibility/uploadify incompatible acquisition" and found many articles, but I read them carefully and found that they were all written by myself. The main reason is (the following section is excerpted from: http://blog.csdn.net/longlong821/article/details/7785703 ):

    Jquery uploadify can be uploaded normally under ie. During asynchronous upload, each file is submitted to the server for a request. Each request requires security verification, session and cookie verification. Yes, that's it. Because jquery uploadify uploads data using flash, ie automatically binds local cookie storage to the server every time a data stream request is sent to the backend. But firefox and chrome won't do this, and they will think this is not safe.

    Session, also known as Session status, is the most common status in the Web system and is used to maintain information related to the current browser instance. For example, we can put the username of the logged-on user in the Session, so that we can determine whether the user is logged on by judging a Key in the Session. If the user is logged on, the username is the same.

    We know that Session is a "one-person copy" for each client (or browser instance). When a user establishes a connection with the Web server for the first time, the server will distribute a SessionID to the user as the identifier. SessionID is a random string consisting of 24 characters. Each time a user submits a page, the browser will include this SessionID in the HTTP header and submit it to the Web server, so that the Web server can distinguish the client of the current request page.

    1. Next, combine the examples in http://www.jb51.net/article/40824.htm:

      <Script type = "text/javascript">
      $ (Document). ready (function (){
      $ ("# Fileupload"). uploadify ({
      'Swf ':'/uploadify/scripts/uploadify.swf ',
      'Upload': '/fileupload; jsessionid =$ {pageContext. session. id }',
      'Auto': true,
      'Multi ': false,
      'Buttontext': 'browse ',
      'Filedesc': 'supported formats: jpg/gif/jpeg/png/bmp .',
      'Fileext ':' *. jpg; *. gif; *. jpeg; *. png; *. bmp ',
      'Onuploadsuccess': onUploadSuccess
      });
      });
      </Script>

      The most important part is the red part. Note that the one before jsessionid is a semicolon rather than a question mark. The question mark is passed as a parameter.

      1. Finally, the search is ongoing. Because uploadify depends on flash, we recommend that you install the Adobeflash plug-in for Firefox.

      2. Finally, compile your own uploadify upload example:

        1. Compile the example of jsessionid acquisition, in our project, I put it in the common-session.jsp, the content is as follows (the reason for this writing is that our front and back use different common. to use the same jsessionid for both the frontend and backend servers, use <% @ include file =Common-session.jsp"%> Include in. Note: if you do not do this, they are in two sets of common. in jsp, write the following jsessionid code, and finally find that either the background can be used for upload; the foreground can be used for upload; or the background can be uploaded after the foreground is uploaded once, and vice versa ):

        <% @ Page isELIgnored ="False"%>

        <% @ Page language ="Java"PageEncoding =UTF-8"%>

        <% @ Taglib uri ="Http://java.sun.com/jsp/jstl/core"Prefix ="C"%>

        <%

        String sessionid = session. getId ();

        %>

        "Jsessionid" value = "<% = sessionid %>" scope = "Session"/>

        <Script name = Type = "Text/javascript">

        VarJsessionid = '$ {jsessionid }';

        </Script>

        2. Introduce the above "common-session.jsp in common. jsp

        3. Compile the background java upload logic. Here I use springMVC + Spring + MyBatis, and the background code is as follows (the following code is not what I wrote, I don't think the following java code is standard. Here we allow everyone to hehe and vomit ):

        Package XXXX;

         

        Import java. io. File;

        Import java. io. InputStream;

        Import java. util. ArrayList;

        Import java. util. Calendar;

        Import java. util. HashMap;

        Import java. util. List;

        Import java. util. Map;

        Import net. sf. json. JSONObject;

         

        Import org. apache. log4j. Logger;

        /** Skip some code here **/

         

        @ Controller

        @ RequestMapping (value = "/import", method = {RequestMethod. GET, RequestMethod. POST })

        Public class ImportController extends BaseController {

        /** Used to print logs */

        Private static final Logger logger = Logger

        . GetLogger (SpecialController. class );

         

        /**

        * Upload images

        * @ Param

        * @ Param imageFile

        * @ Return

        */

        @ RequestMapping (value = "/uploadPicture", produces = "text/json ")

        @ ResponseBody

        Public String uploadPicture (@ RequestParam ("file") MultipartFile imageFile ){

        Map Result = new HashMap ();

        If (! ImageFile. isEmpty ()){

        Try {

        Calendar calendar = Calendar. getInstance (); // gets the current time

        // Time path, decompress the file, and create a folder by year, month, and day

        String dataPath = "/" + calendar. get (Calendar. YEAR) + "/"

        + (Calendar. get (Calendar. MONTH) + 1) + "/" + calendar. get (Calendar. DATE) + "/";

        // Original file name

        String srcName = imageFile. getOriginalFilename ();

        // Obtain the suffix of the uploaded file

        String suffix = srcName. substring (srcName. lastIndexOf (".") + 1,

        SrcName. length (). toLowerCase ();

        // Generate a 32-bit random id for extracting the file directory

        String uuid = UUIDGenerator. generate ();

        // New file name, random uuid;

        String picName = uuid + "." + suffix;

         

        // Upload the image generation path

        String imgPath = ExtendedServerConfig. getInstance ()

        . GetStringProperty ("THUMBNAIL_PATH") + ExtendedServerConfig. getInstance ()

        . GetStringProperty ("BACKGROUND_IMG_PATH") + dataPath;

        // Generate the image preview path

        String picturePath = ExtendedServerConfig. getInstance ()

        . GetStringProperty ("BACKGROUND_IMG_PATH") + dataPath + picName;

        // If the folder does not exist, create

        File destfile = new File (imgPath );

        If (! Destfile. exists ()){

        Destfile. mkdirs ();

        }

        // Write an object

        InputStream fi = imageFile. getInputStream ();

        // Upload a file and write it to the configuration folder.

        FileUtils. writeFile (fi, imgPath + picName );

        File file = new File (imgPath + picName );

        If (file. exists ()){

        Result. put ("imgPath", picturePath); // The preview path of the returned image.

        Result. put ("ilename", srcName );

        }

        } Catch (Exception e ){

        E. printStackTrace ();

        }

        }

         

        Return JSONObject. fromObject (result). toString ();

        }

        }

        4. Compile the js upload method of uploadify:

        /**

        * Upload background images

        *@ ParamId of the "select" button in uploadId background settings

        *@ ParamThe preview image of the "image" in the imgDivId background settingsDivId

        *@ ParamSetting imgSrcId background"ImgThe id of the tag.SrcUsed for value assignment

        *@ ParamThe value of the text box hidden by bgImgPath stores the image path.

        *@ ParamChildPathOfSelectedElement indicates the selected

        *@ ParamPosFlag indicates who to set the title

        * "0": indicates the title.

        * "1": indicates the list

        */

        FunctionUploadBackgroundImg (uploadId, imgDivId, imgSrcId, bgImgPath, childPathOfSelectedElement, posFlag ){

         

        $ ("#" + UploadId). uploadify ({

        // Automatic upload?

        'Auto ':True,

        'Height': 37,

        'Swf ': scriptsPath + "/uploadify/uploadify.swf ",

        // Container ID after file selection

        'Queue id': 'uploaditemlist ',

        'Fileobjname': 'file ',

        // Upload Handler

        'Upload': basePath + '/import/uploadPicture. action; jsessionid =' + jsessionid,

        // File suffix that can be uploaded

        'Filetypeexts': '*. jpg; *. gif; *. png ;',

        // Size limit of uploaded files

        'Filesizelimmit ': '300mb ',

        // Upload quantity

        'Queuesizelimit ': 1,

        'Queue id': 'filequeue ',

        // Upload to the server, and the server returns the corresponding information to the data

        'Onuploadsuccess ':Function(File, data, response ){

        VarO = $. parseJSON (data );

        VarImgPath = o. imgPath;

        If(ImgPath = "" | imgPath =Null){

        Alert ("Image Upload Failed ");

        }Else{

        $ ("#" + ImgDivId). show ();

        VarPath = vPath + imgPath;

        $ ("#" + ImgSrcId). attr ("src", path );

        $ ("#" + BgImgPath). val (imgPath );

        VarId = selectedElementInfo. get ("id"); // obtain the property value of the id

        $. TplComponentListSetting. removeCss (id, childPathOfSelectedElement, "background-image"); // remove the original background image

        VarStyleCss = $ ("# generatedCss"). text ();

        VarStyleText = "#" + id + childPathOfSelectedElement + "{background-image: url ('" + path + "')! Important ;}";

        // Replace or splice at the end

        StyleCss + = "\ r \ n" + styleText;

        $ ("# GeneratedCss"). text (styleCss );

         

        // Indicates the title

        If("0" = posFlag ){

        // Set related parameter information

        $ ("." + Id + "_ titleBackgroundAbsoluteImg"). val (path );

        $ ("." + Id + "_ titleBackgroundRelativeImg"). val (imgPath );

        }

        // Indicates the list

        Else If("1" = posFlag ){

        Console. log ("temporarily omitted here ");

        }

        }

        }

        });

        }

        Note the above 'upload': basePath + '/import/uploadPicture. action; jsessionid =' + jsessionid,


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.